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

后端 未结 12 2500
礼貌的吻别
礼貌的吻别 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:38

    Is there any difference between the following code?

    No, there is no functional difference between the two code samples in your question. .click(fn) is a "shortcut method" for .on("click", fn). From the documentation for .on():

    There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

    Note that .on() differs from .click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas .click() does not. When .on() is called without a selector parameter, it behaves exactly the same as .click(). If you want event delegation, use .on().

提交回复
热议问题