如何在jquery链接中的选择器后面使用multiple.find()
How to use multiple .find() after selector in jquery chaining?
基本上标题是怎么说的-我想知道是否有办法在同一个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");
相关文章:
- .Find()仅显示可见元素
- SharePoint 2010 Jquery/JSON Rest Multiple OR语句-如何
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- Unit-testing multiple use cases with Karma & Mocha.js
- Webiopi multiple button css
- 他们是如何使用angular/jqLite find()方法按属性名称和值选择元素的?ng conf 2015
- jQuery find() Issue
- 使用jquery Find()在复选框中查找图像
- strongloop script.js run find in before delete方法:如何同步运行异步方法
- 在另一个Find(..)的回调内部查找,如何逃离回调地狱
- 如何防止在jquery中的文本框中输入multiple+
- Animation cuts off multiple lines of text in <p>
- Elm Native with Multiple Arity
- $(e.target).find和template.find('input').value之间有什么区别
- 为什么我得到了一个“;未定义的“;使用“”从Find()返回值;这个“;论点
- .map-find元素一旦通过AJAX加载
- MongoDB collection.find()查询挂起
- 如何在jQuery中使用find
- 无法将参数传递给mongo find集合
- 如何在jquery链接中的选择器后面使用multiple.find()