jQuery.click() vs onClick

前端 未结 17 1754
情话喂你
情话喂你 2020-11-21 07:35

I have a huge jQuery application, and I\'m using the below two methods for click events.

First method

HTML

17条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 08:08

    From what I understand, your question is not really about whether to use jQuery or not. It's rather: Is it better to bind events inline in HTML or through event listeners?

    Inline binding is deprecated. Moreover this way you can only bind one function to a certain event.

    Therefore I recommend using event listeners. This way, you'll be able to bind many functions to a single event and to unbind them later if needed. Consider this pure JavaScript code:

    querySelector('#myDiv').addEventListener('click', function () {
        // Some code...
    });
    

    This works in most modern browsers.

    However, if you already include jQuery in your project — just use jQuery: .on or .click function.

提交回复
热议问题