$('#id tag')与$('#id').find('tag')-哪个更好? [英] $('#id tag') vs. $('#id').find('tag') - which is preferable?

查看:106
本文介绍了$('#id tag')与$('#id').find('tag')-哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪种选择更好,特别是在速度方面:

I want to know which option is better, particularly in terms of their speed:

$('#id tag')...

$('#id').find('tag')...

此外,如果将id和/或tag更改为class或类似input:checked的东西,是否也会得到相同的答案?

Also, would the same answer apply if you change id and/or tag to, say, a class or something like input:checked?

例如,哪个更好:$('#id input:checked')...$('#id').find('input:checked');?

推荐答案

您的决定可以基于以下三点:

You can base your decision on 3 things:

可读性

这与您的两个给定选择器没有太大区别.就我而言,我更喜欢$('#id').find('inner')语法,因为它可以更准确地描述其实际功能.

This is not much of a difference with your two given selectors. For my part, I prefer the $('#id').find('inner') syntax because it describes more accurately what it is actually doing.

可重用性

如果您的代码的其他部分使用相同的id选择器(或其上下文中的某些内容),则可以缓存选择器并重新使用它.我自己发现,很难重构像这样的$('#id inner')编写的代码,因为您必须先解码css选择器,然后才能继续并找到可能的改进.

If you have other parts of your code use the same id selector (or something in its context), you can cache the selector and reuse it. I myself find it harder to refactor code that has been written like this $('#id inner'), because you have to decode the css selector first before you can move on and find possible improvements.

想象这两种情况并没有太多复杂性

Imagine these two cases with not much complexity

$('#hello .class_name tag').doThis();
$('#hello .other_name input').doThat();

还有另一种情况

$('#hello').find('.class_name tag').doThis();
$('#hello').find('.other_name input').doThat();

我认为第二个示例对您缓存ID选择器"大喊大叫,而第一个则没有.

I think the second example screams at you «Cache the id selector», and the first does not.

速度

性能始终是一个不错的选择,在这种情况下,带有find的id选择器在大多数浏览器中都能做得更好,因为它首先建立了上下文,并且可以将降序选择器应用于较小的元素子集.

Performance is always a good point, and in this case, the id selector with the find does the better job in most browsers, because it establishes the context first and can apply the descending selector to a smaller subset of elements.

如果您想了解有关context-vs子集的更多信息,这是一项很好的性能测试jQuery中的选择器性能. id的子集通常是 规则.当然,您可以获得不同的结果,但是在大多数情况下,它们会得到.

Here's a good performance test, if you want to know more about context-vs subset selectors performance in jQuery. Subsets of ids generally rule. Of course you can get different results, but in most cases, they do.

所以,从我的角度来看,子集选择器的取值范围是3到0.

So, 3 to 0 for subset selectors from my point of view.

这篇关于$('#id tag')与$('#id').find('tag')-哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆