开发者

what is the difference between $("#context .searched") and $(".searched",$("#context"))?

开发者 https://www.devze.com 2023-01-13 12:21 出处:网络
I had that question in mind for a long time. Theo开发者_如何学运维retically, jQuery core function accepts an optional value that can be a DOM element- $(\".searched\",$(\"#context\")[0]) - or a jQuer

I had that question in mind for a long time.

Theo开发者_如何学运维retically, jQuery core function accepts an optional value that can be a DOM element - $(".searched",$("#context")[0]) - or a jQuery object - $(".searched",$("#context") ) . I discovered that last question reading that fine article.

But i really cant see the difference between use a context and pass a more complex css expression. If there is no difference in the way it works, is there any perfomance difference?

Thanks


It gets converted to a DOM element (in Sizzle, the context portion) to search in either of your cases, ultimately doing a .find() under the covers.

If you're concerned about performance (why not be as fast as possible?), you should use this instead:

$("#context .searched")

This version gets converted back into a jQuery object:

$("#context")[0]

So it's a bit slower on the jquery side, since it has to be wrapped in a jquery object before the .find() call, that performance difference is very minimal, but it's the only difference so I'm noting it :)


The major difference would be that $(".searched", context); can take a variable as a context as well. It is effectively doing $(context).find('.searched'); under the hood, and I think the second version is more readable anyway, so I usually use that.

The use for this situation would be something like this:

$.fn.highlightSearch = function() {
  return this.each(function() {
    $('.searched', this).addClass('highlighted');
    // the commented line performs the same thing:
    // $(this).find('.searched').addClass('highlighted');
  });
};

$('#context').highlightSearch();
$('.somethingElse').highlightSearch();

Notice that in this case, you can't simply append the new selector on the end of the original.

If you have no other reason to hold a copy of $('#context'), then using $('#context .searched') is going to be quicker, and simpler. However, if you already had $('#context') stored in a variable, its better to use .find(select) or the $(selector, context) form to search for your contained elements.


Readability: a CSS selector like $("#context .searched") is far more readable than the other.

0

精彩评论

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

关注公众号