简体   繁体   中英

jQuery double object constructor - e.g. $($(this))

Assume you have the following code:

function name() {
    $(this).css('background', 'red');
}

$('selector1').click(name);

$('selector2').click(function () {
    name.call($(this).parent());
});

Now, when the function is called by clicking on 'selector1' this is an HTML object and $(this) a jQuery object, but if the function is called by clicking on 'selector2' this is already a jQuery object so what is $(this) ?

I know I could do something like name.call($(this).parent()[0]); to get an HTML object, but my question is what happens when you do something like $($(this)) or $($('selector')) ? What is the result of that and, most impotently, is there any harm in using such a construct?

$(this) when this is already a jQuery object creates a copy of the jQuery object.

From the jQuery docs :

Cloning jQuery Objects

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM