开发者

Does jQuery modify the target element at all when creating an event handler?

开发者 https://www.devze.com 2023-04-03 10:25 出处:网络
For example: $(\"myElement\").click(function(){ alert(\"Clicked!\"); }; Has the #myElement been modified, it\'s onclick attribu开发者_开发技巧te set, or did jQuery just set a listener?The click() f

For example:

$("myElement").click(function(){
alert("Clicked!");
};

Has the #myElement been modified, it's onclick attribu开发者_开发技巧te set, or did jQuery just set a listener?


The click() function does not change any DOM attributes.

It adds a listener for that particular jQuery element.

The same goes for .change(), .keyup(), ... etcetera.


jQuery sets a listener if used .click();


It does not modify the element.

jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements


Looking at the jQuery 1.6.2 source:

$("myElement").click(...) calls: $("myElement").bind('click', ...) 
which then calls: jQuery.event.add(...) 
which ultimately does either elem.addEventListener(...) or elem.attachEvent(...)

So, we can say conclusively that it is not setting the onclick attribute (which is as we would expect since addEventListener is more extensible).

BUT, when I step through the .click() function, deep inside, an attribute is being added to the DOM object. It's related to jQuery's data function and it in this piece of code in jQuery's data function which is called from event.add(...). It looks like it's some sort of guid identifier that jQuery uses to keep track of which object is which without keeping a DOM reference (which can lead to memory leaks). The code that adds that attribute is here:

   if ( !id ) {
        // Only DOM nodes need a new unique ID for each element since their data
        // ends up in the global cache
        if ( isNode ) {
            elem[ jQuery.expando ] = id = ++jQuery.uuid;
        } else {
            id = jQuery.expando;
        }
    }

So, in conclusion, jQuery is not touched the .onclick attribute, but it is setting at least one other attribute on the DOM object when setting the first event handler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号