jQuery.click() vs onClick

前端 未结 17 1475
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2020-11-21 08:11

    Neither one is better in that they may be used for different purposes. onClick (should actually be onclick) performs very slightly better, but I highly doubt you will notice a difference there.

    It is worth noting that they do different things: .click can be bound to any jQuery collection whereas onclick has to be used inline on the elements you want it to be bound to. You can also bind only one event to using onclick, whereas .click lets you continue to bind events.

    In my opinion, I would be consistent about it and just use .click everywhere and keep all of my JavaScript code together and separated from the HTML.

    Don't use onclick. There isn't any reason to use it unless you know what you're doing, and you probably don't.

    0 讨论(0)
  • 2020-11-21 08:14

    $('#myDiv').click is better, because it separates JavaScript code from HTML. One must try to keep the page behaviour and structure different. This helps a lot.

    0 讨论(0)
  • 2020-11-21 08:15

    Go for this as it will give you both standard and performance.

     $('#myDiv').click(function(){
          //Some code
     });
    

    As the second method is simple JavaScript code and is faster than jQuery. But here performance will be approximately the same.

    0 讨论(0)
  • 2020-11-21 08:15

    The first method of using onclick is not jQuery but simply Javascript, so you do not get the overhead of jQuery. The jQuery way can expanded via selectors if you needed to add it to other elements without adding the event handler to each element, but as you have it now it is just a question if you need to use jQuery or not.

    Personally since you are using jQuery I would stick with it as it is consistent and does decouple the markup from the script.

    0 讨论(0)
  • 2020-11-21 08:19

    Well, one of the main ideas behind jQuery is to separate JavaScript from the nasty HTML code. The first method is the way to go.

    0 讨论(0)
提交回复
热议问题