开发者

jQuery: Is there a functional difference between $('.selector', myContext) and myContext.find('.selector')?

I feel like $('.selector', myContext) and myContext.find('.selector') are two identical ways to get the same information. Is there a practical reason when you would use one over the other? Speed perhaps开发者_Python百科?


$('.selector', myContext) and $(myContext).find('.selector') are completely equivalent:

From the jQuery 1.4.2 source (core.js):

//...

// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
    return jQuery( context ).find( selector );
}

//...


Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

From: http://api.jquery.com/jQuery/#jQuery1


The first involves slightly less characters of code, but other than that the same thing


When a new jQuery object is created the constructor tries to figure out what was passed in. When context is a DOMElement jQuery transforms $(selector, context) into $(context).find(selector). You can avoid much of the logic the constructor does including some string parsing by making this change yourself. (excerpt from the following post : http://engineeredweb.com/blog/10/12/3-tips-make-your-jquery-selectors-faster/ )

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜