search

Home  >  Q&A  >  body text

javascript - Two jQuery operations trigger the same function, how to optimize the writing?

$('#button').click(function() {
    todo();
});

$('#input').keydown(function(e) {
    if(e.keyCode == 13) {
        todo();
    }
});

For example, if you click a button or press Enter in the input box to perform the same operation, can it be optimized into the following type of code:

$('#buttonA,#buttonB').click(function(){
    todo....
});

phpcn_u1582phpcn_u15822779 days ago444

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-05-19 10:36:29

    Generally I like to use hosting

    $('.container').on('click', '.btn', function(e) {
        // 只有在点击 .container 下的 .btn 元素才运行, this 只想的是 .btn 元素
        // 而且 不需要考虑你的 .btn 是否存在, 是否后加载
    });

    If your two operations have something in common, you can use the same class name to identify and bind events
    If they are of different types, your first method is fine

    reply
    0
  • Cancelreply