有区别,并不像其他人认为的那样微妙。
编辑:外行人的每个例子:
- 打电话给镇上所有的蓝色房子(上下文),如果简在那里,请揭发她的帽子。
- 呼叫镇上的所有建筑物(还没有上下文)。如果它是一座蓝色的房子(添加上下文)并且 Jane 在那里,请揭发她的帽子。
让我们分解它选择的内容。
首先我们有:上下文选择器 http://api.jquery.com/jQuery/#jQuery-selector-context
$('input.current_title', '#storePreferences').prop('disabled', false);
这表示: 在上下文中使用选择器。 http://api.jquery.com/jQuery/#jQuery-selector-context
虽然这种形式可能有效,但实际上应该是:
$('input.current_title', $('#storePreferences')).prop('disabled', false);
或
var myContext = $('#storePreferences');
$('input.current_title', myContext).prop('disabled', false);
这符合上下文选择器的要求:“A DOM Element, Document, or jQuery to use as context”。
这就是说:使用上下文,在里面找到选择器。等价物是:
$('#storePreferences').find('input.current_title').prop('disabled', false);
这就是内部发生的事情。找到 '#storePreferences' 并在其中找到所有 'input.current_title' 匹配的元素。
那么我们有:后代选择器
$('#storePreferences input.current_title').prop('disabled', false);
这是一个后代选择器(“祖先后代”)http://api.jquery.com/descendant-selector/,它表示:找到 #storePreferences 元素内的所有 input.current_title 元素。这就是棘手的地方! - 这正是它的作用 -
找到所有input.current_title(任何地方),然后找到#storePreferences元素内的那些。
因此,我们遇到了 jQuerys 的 Sizzle 从右到左选择器 - 所以它最初会发现(可能)比它需要的更多,这可能是性能损失/问题。
因此形式为:
$('#storePreferences').find('input.current_title').prop('disabled', false);
很可能会比后代版本表现更好。