两者之间有什么区别吗?
$('input.current_title', '#storePreferences').prop('disabled', false);和
$('#storePreferences input.current_title').prop('disabled', false);发布于 2013-05-07 23:44:20
是有区别的,而且并不像其他人认为的那样微妙。
编辑:Layman的每个示例:
让我们来分析一下它选择的内容。
首先我们有: Context 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/,它说:查找#storePreferences元素内的所有input.current_title元素。这就是它变得棘手的地方!-这正是它所做的-
查找所有input.current_title (anywhere),然后查找#storePreferences元素中的那些元素。
因此,我们遇到了jQuerys的Sizzle从右到左的选择器--所以它最初发现的(潜在的)比它需要的更多,这可能是一个性能问题。
因此,形式为:
$('#storePreferences').find('input.current_title').prop('disabled', false);最有可能比后代版本执行得更好。
发布于 2019-12-05 03:40:22
在你的例子中,我相信没有什么不同。
当您开始选择特定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);https://stackoverflow.com/questions/16422478
复制相似问题