jQuery中的Context与Selector特定 [英] Context vs. Selector specificy in jQuery

查看:46
本文介绍了jQuery中的Context与Selector特定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时可以通过使用分层选择器指定可以找到特定元素的范围,即:

There are times when one can specify the scope in which a particular element might be found either by using a hierarchical selector, ie:

$('#someParent .someChildren')

...或使用上下文,即:

...or by using context, ie:

$('.someChildren', $('#someParent'))

我知道有些时候人们不能使用前者,所以显然后者很有用。但是在我提出的情况下,哪个更好,为什么?

I know there are times when one can't use the former, so obviously the latter is useful. But in situations like the one I present, which is better and why?

推荐答案

这个:

$('.someChildren', $('#someParent'))

简单地转换成:

$('#someParent').find('.someChildren')

运行一些测试后。所以实际的考虑因素是:

after running some tests. So the actual consideration will be between:

$('#someParent .someChildren')

和:

$('#someParent').find('.someChildren')

(考虑到分析和转换)。

那么这两者中的哪一个更快可能与浏览器有关。我个人从不使用 context 参数。

So which of those two is faster will likely be browser dependent. I personally never use the context parameter.

如果你想要 .find() ,然后我直接使用它,而不是让jQuery为你翻转它。

If you want a .find(), then I'd just use it directly instead of having jQuery flip it for you.

人们经常使用 context 当需要设置 this 作为 .find()的根时。

People often use the context when the need to set this as the root of the .find().

$('.someChildren', this)

...所以在这种情况下,这样做会更快:

...so in that case, it is faster to do this:

$(this).find('.someChildren')

...更容易理解我的意见。

...and more easily understandable in my opinion.

这篇关于jQuery中的Context与Selector特定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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