什么是“背景”在jQuery选择器? [英] What is "context" in jQuery selector?
问题描述
Is there any difference between
$('input.current_title', '#storePreferences').prop('disabled', false);
和
$('#storePreferences input.current_title').prop('disabled', false);
?
推荐答案
存在差异,并不像其他人所认为的那样微妙。
编辑: Layman的每个例子:
Layman's example of each:
- 如果Jane在那里,请打电话给镇上的所有蓝色房子(上下文),小费她的帽子。
- 调用镇上的所有建筑物(尚无上下文)。如果它是一个蓝色的房子(添加上下文)而Jane就在那里,请小费她的帽子。
让我们分解它所选择的内容。
Let's break down what it selects.
首先我们有:上下文选择器 http://api.jquery.com/jQuery/#jQuery-selector-context
$('input.current_title', '#storePreferences').prop('disabled', false);
这说:在上下文中使用选择器。 http://api.jquery.com/jQuery/#jQuery-selector-context
This says: use a selector in context. http://api.jquery.com/jQuery/#jQuery-selector-context
虽然这个表格很可行,但它应该是:
While this form MIGHT work, it should really be:
$('input.current_title', $('#storePreferences')).prop('disabled', false);
OR
var myContext = $('#storePreferences');
$('input.current_title', myContext).prop('disabled', false);
这符合满足上下文选择器的要求:DOM元素,文档或jQuery到用作上下文。
This meets the requirement for a context selector being met: "A DOM Element, Document, or jQuery to use as context".
这说:使用上下文,在选择器内找到。相当于:
This says: using the context, find inside that the selector. An equivalent would be:
$('#storePreferences').find('input.current_title').prop('disabled', false);
这是内部发生的事情。找到'#storePreferences'
,然后查找所有'input.current_title'
匹配元素。
Which is what happens internally. Find '#storePreferences'
and in that find all the 'input.current_title'
matching elements.
然后我们有:后代选择器
$('#storePreferences input.current_title').prop('disabled', false);
这是一个后代选择器(祖先后裔) http://api.jquery.com/descendant-selector/ 说:找到所有 input.current_title
#storePreferences
元素内的元素。这就是它变得棘手的地方! - 这完全是它的作用 -
This is a Descendant Selector ("ancestor descendant") http://api.jquery.com/descendant-selector/ which says: find all the input.current_title
elements inside the #storePreferences
element. THIS IS WHERE IT GETS TRICKY! - that is EXACTLY what it does -
找到所有 input.current_title
(任何地方),然后在 #storePreferences
元素中找到那些。
finds ALL the input.current_title
(anywhere), then finds those INSIDE the #storePreferences
element.
因此,我们遇到jQuerys的Sizzle权利左选择器 - 所以它最初发现比它需要的更多(可能),这可能是性能命中/问题。
Thus, we run into jQuerys' Sizzle right to left selector - so it initially finds MORE(potentially) than it needs which could be a performance hit/issue.
因此形式为:
$('#storePreferences').find('input.current_title').prop('disabled', false);
最有可能比Descendant版本表现更好。
would perform better than the Descendant version most likely.
这篇关于什么是“背景”在jQuery选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!