【问题标题】:Difference between the descendant selector and the .find() method in jquery selectorsjquery选择器中后代选择器和.find()方法的区别
【发布时间】:2019-12-10 15:45:41
【问题描述】:

我想知道这两个jquery代码之间是否存在任何差异:

$("div#intro .head")

$("div#intro").find(".head")

谢谢!

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    正如所写,它们都产生相同的输出,但是带有.find 的第二个需要首先为所有匹配div#intro 的元素构造一个jQuery 对象,所以第一个可能更可取(更不用说更简洁了) .

    也就是说,.find 可以做许多后代选择器不能做的事情:

    • 使用 jQuery 对象作为参数

    const $greenSpans = $('span.green');
    
    // ...
    // later:
    
    const found = $('div').find($greenSpans);
    console.log(found.length, found[0]);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="green">1</span>
    <div>
      <span class="green">2</span>
    </div>
    • 使用 HTMLElement 作为参数

    // not so useful, because you already have a reference to the element to change
    
    const greenSpan = document.querySelectorAll('span.green')[1];
    
    // ...
    // later
    
    const found = $('div').find(greenSpan);
    console.log(found.length, found[0]);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="green">1</span>
    <div>
      <span class="green">2</span>
    </div>
    • 对已创建的 jQuery 对象进行操作

    const $div = $('div');
    
    // ...
    // later
    
    const found = $div.find('span');;
    console.log(found.length, found[0]);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="green">1</span>
    <div>
      <span class="green">2</span>
    </div>

    【讨论】:

    • 嗯,你认为第一个比第二个更省时吗?
    • 是的 - 就像我在答案中所说,第二个带有.find 需要首先为所有匹配div#intro 的元素构造一个jQuery对象,所以它的效率较低.
    猜你喜欢
    • 2014-11-02
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    相关资源
    最近更新 更多