javascript - Two jQuery operations trigger the same function, how to optimize the writing?
phpcn_u1582
phpcn_u1582 2017-05-19 10:34:29
0
1
417
$('#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_u1582
phpcn_u1582

reply all(1)
刘奇

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template