如何在jquery链接中的选择器后面使用multiple.find()

How to use multiple .find() after selector in jquery chaining?

本文关键字:multiple find 选择器 jquery 链接      更新时间:2023-09-26

基本上标题是怎么说的-我想知道是否有办法在同一个jQuery选择器上多次使用.find()。或者多次使用.find()不是正确的方法?

以下是我正在努力实现的目标:

HTML

<div id="foo">
    <h2>A Header</h2>
    <p>Some text</p>
</div>

JS

$("#foo").find("h2").html("New header");
$("#foo").find("p").html("New text");

Webstorm抱怨重复的jQuery选择器。有其他更好的方法吗?

您可以使用next():

$("#foo").find("h2").html("New header")
         .next("p").html("New Text");

要在链接中返回到上一个集合,我们可以使用end()

$("#foo")
    .find("h2")
        .html("New header")
        .end()
    .find("p")
        .html("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
    <h2>A Header</h2>
    <p>Some text</p>
</div>

在链接中使用.find()后,使用.addBack()返回到第一个选择器。

$("#foo").find("h2").html("New header").addBack().find("p").html("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <h2>A Header</h2>
  <p>Some text</p>
</div>

"正确的方法"(至少是最简单的方法)是使用基本的CSS选择器语法:

$("#foo h2").html("New header");
$("#foo p").html("New text");

或者更具体地说,这个:

$("#foo>h2").html("New header");
$("#foo>p").html("New text");

第一个示例以任何级别的foo的后代h2为目标,而第二个示例以直接后代h2为目标。

至于尝试做这样的事情:

x = $("#foo").find("h2").find("p");

这相当于:

x = $("#foo h2 p");

(您可以在执行语句并查看x.selector之后进入调试来验证这一点。)这意味着您正在foo:中的标头中查找段落

<div id="foo">
    <h2>A Header
        <p>**Selector would find this**</p>
    </h2>
</div>

在你的例子中没有这样的例子。

<div id="foo">
  <h2>A Header</h2>
  <p>Some text</p>
</div>
var $foo = $("#foo");
$foo.find("h2").html("New header");
$foo.find("p").html("New text");

或者,如果可能的话:

<div id="foo">
  <h2>A Header</h2>
  <p>Some text</p>
</div>
var htmlString = '<h2>New header</h2><p>New text</p>';
$("#foo").html( htmlString );

它说duplicated jQuery selector是因为您应该(在可能的情况下)始终缓存jQuery选择器,因为每次需要$("#foo")时都会浪费时间
所以,你的代码应该变成这样的

HTML

<div id="foo">
  <h2>A Header</h2>
  <p>Some text</p>
</div>

JS

var foo = $("#foo");
foo.find("h2").html("New header");
foo.find("p").html("New text");