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

Ben*_*rey 5 javascript jquery event-handling javascript-events

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

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

$(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
    }
});
Run Code Online (Sandbox Code Playgroud)

要么:

$(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
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*ner 2

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

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