一个on()内的多个on()或switch()

时间:2013-06-10 19:30:00

标签: javascript jquery javascript-events event-handling

我的页面上有一个菜单,我正在编写脚本,设置菜单按钮的所有点击事件。每个按钮都会调用自己的方法,因此必须明确设置。

我的问题很简单,在这种情况下,最好使用以下哪两种方法:

$(document).on('click','#menu .button', function(){
    switch($(this).attr('id')){
        case 'foo_button':
            // Set the event for the foo button
        break;
        case 'bar_button':
            // Set the event for the bar button
        break;
        // And the rest of the buttons
    }
});

或者:

$(document).on('click','#foo_button',function(){
    // Set the event for the foo button
});
$(document).on('click','#bar_button',function(){
    // Set the event for the bar button
});
// And the rest of the buttons

我原本认为选项1会更好,因为它只设置一个事件......但是,每次单击菜单按钮都会调用此事件,因此很难知道哪个更有效。

1 个答案:

答案 0 :(得分:2)

如果每个不同的按钮ID的处理函数真的不同,那么应该使用自己对on()的调用来注册每个按钮ID。

这可能不会对代码的性能产生明显的影响,但它将使其他开发人员(甚至自己的维护)在将来更容易阅读。