Difference between .on('click') vs .click()

后端 未结 12 2474
礼貌的吻别
礼貌的吻别 2020-11-21 05:22

Is there any difference between the following code?

$(\'#whatever\').on(\'click\', function() {
     /* your code here */
});

and

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 05:37

    .on() is the recommended way to do all your event binding as of jQuery 1.7. It rolls all the functionality of both .bind() and .live() into one function that alters behavior as you pass it different parameters.

    As you have written your example, there is no difference between the two. Both bind a handler to the click event of #whatever. on() offers additional flexibility in allowing you to delegate events fired by children of #whatever to a single handler function, if you choose.

    // Bind to all links inside #whatever, even new ones created later.
    $('#whatever').on('click', 'a', function() { ... });
    

提交回复
热议问题