50

有没有区别

$('input.current_title', '#storePreferences').prop('disabled', false);

$('#storePreferences input.current_title').prop('disabled', false);

?

4

3 回答 3

66

有区别,并不像其他人认为的那样微妙。

编辑:外行的每个例子:

  • 打电话给镇上所有的蓝色房子(上下文),如果简在那里,请脱掉她的帽子。
  • 呼叫镇上的所有建筑物(还没有上下文)。如果它是一座蓝色的房子(添加上下文)并且简在那里,请脱掉她的帽子。

让我们分解它选择的内容。

首先我们有:上下文选择器 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);

这满足了满足上下文选择器的要求:“用作上下文的 DOM 元素、文档或 jQuery”。

这说:使用上下文,在选择器内部找到。等效的将是:

$('#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/它说:找到input.current_title元素内的所有#storePreferences元素。这就是棘手的地方!- 这正是它的作用 -

找到所有 input.current_title(任何地方),然后找到那些 INSIDE the #storePreferenceselement

因此,我们遇到了 jQuerys 的 Sizzle 从右到左选择器 - 所以它最初发现 MORE(可能)比它需要的更多,这可能是性能损失/问题。

因此形式为:

$('#storePreferences').find('input.current_title').prop('disabled', false);

最有可能比后代版本表现更好。

于 2013-05-07T15:44:20.277 回答
34

$('input.current_title', '#storePreferences').prop('disabled', false);和有什么区别$('#storePreferences input.current_title').prop('disabled', false);吗?

是的,但它很微妙

不同之处在于如何选择元素。

$('input.current_title', '#storePreferences');

相当于1

$('#storePreferences').find('input.current_title');

等同于:

$('#storePreferences input.current_title');

即使相同的元素会受到影响。

它们不一样的原因是 using允许在调用时find返回上下文。#storePreferencesend

1:jQuery v1.9.1 源代码中的第 194-202 行
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
    return ( context || rootjQuery ).find( selector );

// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
    return this.constructor( context ).find( selector );
}

在您的问题的上下文中,将修改相同的元素,因此在功能上没有区别,但重要的是要了解您使用的选择器的更广泛含义。

于 2013-05-07T15:14:12.817 回答
0

在你的例子中,我相信差别不大。

当您开始在特定 DOM 元素中选择多个元素时,它会更好地使用。

// Get the div in the body with the id of storePreferences
var sp = $('body div#storePreferences');


// jQquery will only look for **input.current_title** **input.name** **input.age** in side **sp** div in the DOM.
// Faster
$('input.current_title', sp).prop('disabled', false);
$('input.name', sp).prop('disabled', false);
$('input.age', sp).prop('disabled', false);




// jQquery will look for **input.current_title** in entire DOM
// Slower
$('#storePreferences input.current_title').prop('disabled', false);
于 2019-12-04T19:40:22.313 回答