Is there any reason to have nested calls to $ (jQuery)?

I was poking around the source code of a website when I came across some code like this:

$($('#newForm_step1')).hide("slide", { direction: "left" }, 0);

and this:

$($($('.breadcrumbs')[0]).children().last()).html("...");

I've never seen the $ ( jQuery ) function used this way, and I was wondering if there'd be any practical reason to do something like this? To the best of my knowledge, wrapping a jQuery object with a call to $ simply returns a jQuery object for the same selector, and methods on jQuery objects return this , so I don't see why one would need nested calls to $ .


No, there is no reason to do this.

In the first example, $($(...)) is redundant. There is absolutely no effect in immediately wrapping a jQuery object in another jQuery object.

The line should read

$('#newForm_step1').hide("slide", { direction: "left" }, 0);

In the second example, $(...)[0] returns a raw DOM element, so it's wrapped again before having jQuery's .children().last() invoked on it. The result of that is already a jQuery object, so there is no need to re-wrap it, and the "unwrapping" could have been avoided by calling .first() instead of [0] .

The line should read

$('.breadcrumbs').first().children().last().html("...");

There's no necessary to wrap jQuery object with jQuery. That will just result the same but over-coding and redundant.

But when you have DOM Object then you need to wrap with jQuery so that it will be jQuery object.

Taking your example:

$('.breadcrumbs')[0];//[0] converts to JavaScript Object

Now, if you want to work with jQuery again, you may then wrap with jQuery:

$($('.breadcrumbs')[0]);//is now a jQuery Object

But with this example is unnecessary because you can do just like this:

$('.breadcrumbs:eq(0)');//selects first .breadcrumbs element

However, if you have some DOM Object rather than jQuery object then you need jQuery wrapper to work with jQuery methods.


You must remember this:

JavaScript Object needs JavaScript methods to be chained:

javascriptObject.javascriptMethods

Ex-

$('.breadcrumbs')[0].addEventListener();//javascript addEventListener method

jQuery Object needs jQuery methods to be chained:

jQueryObject.jQueryMethods

Ex-

$('.breadcrumbs').on();//jQuery on method
链接地址: http://www.djcxy.com/p/80928.html

上一篇: 序列化不带引号的属性名称

下一篇: 是否有任何理由嵌套调用$(jQuery)?