Javascript 多个on()或一个on()内的开关()

Javascript 多个on()或一个on()内的开关(),javascript,jquery,javascript-events,event-handling,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

我的页面上有一个菜单,目前正在编写脚本,为菜单按钮设置所有单击事件。每个按钮都将调用自己的方法,因此必须显式设置它

简单地说,我的问题是,在这种情况下,以下两种方法中哪一种更好:

$(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
    }
});
或:


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

如果处理程序函数对于每个不同的按钮ID确实不同,则应使用其自己对
on()
的调用来注册每个按钮


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

jQuery已经做到了这一点。@SLaks就像jQuery应用switch语句一样?太棒了,这就是我想知道的+1。你能解释一下为什么吗?
$(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