How does JQuery's .click() work behind the scenes?

前端 未结 3 1986
时光说笑
时光说笑 2021-01-13 04:18

This question is just out of curiosity. I want to know how jquery\'s .click() works behind the scenes.

For instance if I create a button:



        
相关标签:
3条回答
  • 2021-01-13 04:27

    Uses the DOM event model, which is also what happens when you add the onClick(). so basically it registers a listener for the button to fire off the click event and then performs the code you told it to.

    0 讨论(0)
  • 2021-01-13 04:45

    the function is attached to the onclick event on your input but not using the html declaration but plain javascript. Instead of looking in the html code take a look at the DOM tab in firebug, you should find it there.

    In plain javascript it's like

        document.getElementById('myButton').addEventListener('click',function () { alert('hello!');},false);
    
    0 讨论(0)
  • 2021-01-13 04:52

    It will depend on the browser.

    If you're using a browser that supports addEventListener(), they'll add a handler using that.

    Although I'm pretty sure they're actually attaching a function that first repairs/normalizes the event object, then checks the DOM element for the jQuery12345... property and looks up the handler in jQuery.cache and invokes it.

    If you log your element to the console, you'll see a property that looks something like:

    jQuery1296081364954: 1
    

    Then if you log that number to the console from jQuery.cache, you'll see the associated data.

    console.log(jQuery.cache[1]);
    

    ...which will give a structure something like this:

    {
       events:{
          click:[
             { /* object containing data relevant to the first click handler */ }
          ]
       },
       handle:{ /* this may be what initially gets called. Not sure. */ }
    }
    

    Because jQuery does normalize the event object, it isn't quite as simple as just assigning a a handler for you and calling it. I believe it is also done with the cache in order to avoid memory leaks in older browsers.

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