簡體   English   中英

jQuery 選擇器中的“上下文”是什么?

[英]What is “context” in jQuery selector?

有什么區別嗎

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

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

?

有區別,它並不像其他人認為的那樣微妙。

編輯:外行的例子:

  • 打電話給鎮上所有的藍房子(上下文),如果簡在那里,請給她小費。
  • 呼叫鎮上的所有建築物(尚無上下文)。 如果它是一個藍色的房子(添加上下文)並且簡在那里,請揭開她的帽子。

讓我們分解一下它選擇的內容。

首先我們有:上下文選擇器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 (任何地方),然后在#storePreferences元素中找到那些

因此,我們遇到了 jQuery 的 Sizzle 從右到左選擇器 - 所以它最初發現(可能)比它需要的更多,這可能是性能問題/問題。

因此形式為:

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

最有可能比 Descendant 版本表現更好。

$('input.current_title', '#storePreferences').prop('disabled', false);之間有什么區別$('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');

即使相同的元素會受到影響。

他們是不一樣的原因是,使用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 ); }

在您的問題的上下文中,將修改相同的元素,因此功能上沒有區別,但重要的是要了解您使用的選擇器的更廣泛含義。

在您的示例中,我認為幾乎沒有區別。

當您開始選擇特定 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM