简体   繁体   English

选择涉及父级的jQuery元素

[英]Selecting jQuery elements involving parent

Consider following scenarios and jQuery usage variants: 考虑以下场景和jQuery使用变体:

HTML HTML

<ul class="wrapper">
    <li class="item">item 1</li>
    <li class="item">item 2</li>
    <li class="item">item 3</li>
    <li class="item">item 4</li>
</ul>

Usage a. 用法a。

$('.wrapper').find('.item').addClass('active');

Usage b. 用法b。

$('.item', '.wrapper').addClass('active');

My questions are 我的问题

  • Are they identical, in terms of functionality? 它们在功能方面是否相同?
  • Is one perform better than the other? 一个表现比另一个好吗?
  • Assuming they are identical, which one is considered as a better practise? 假设它们是相同的,哪一个被认为是更好的做法?

This $('.item', '.wrapper').addClass('active'); 这个$('.item', '.wrapper').addClass('active');

would be internally translated as 将在内部翻译为

$('.wrapper').find('.item').addClass('active'); .

So i am sure that there is no difference between them. 所以我相信他们之间没有区别。

//HANDLE: $(expr, context) 
//(which is just equivalent to: $(context).find(expr)

I just found the above comments in the jquery source 我刚刚在jquery源代码中找到了上述注释

Performance result may be useful http://jsperf.com/ 性能结果可能有用http://jsperf.com/

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM