我有一个列表,每个列表包含一个文本值。 如何获得具有完全给定文本值的列表对象?
<div id="child4"></div> <div id="child5">ib</div> <div id="child6"></div> <div id="child7">ii</div> <div id="child8">iii</div> <div id="child1" width="200px"></div><div id="child2">i</div> <script type="text/javascript"> alert($("div>div:contains('i')").attr("id")); </script>上面的脚本给了我所有包含文本值i的div。如何解决这个问题,以便我得到一个与'i'具有完全相同文本值的元素?
I have a list each containing a text value. How do I get the list object having exactly a given text value?
<div id="child4"></div> <div id="child5">ib</div> <div id="child6"></div> <div id="child7">ii</div> <div id="child8">iii</div> <div id="child1" width="200px"></div><div id="child2">i</div> <script type="text/javascript"> alert($("div>div:contains('i')").attr("id")); </script>The above script gives me all the div that contains the text value i..How can I fix this so that i get an element having exactly the same text value as 'i'?
最满意答案
$("div > div").filter(function() { return $(this).text() === "i"; });filter方法仅返回与条件匹配的元素。 该条件仅匹配其text为指定字符串的元素。
请注意,在您的示例中,这将不匹配任何内容,因为您的选择器div > div将选择div元素作为另一个div直接子元素,并且示例中的元素没有父div 。
这是运行代码的示例 。 在示例中,我已将选择器更改为div 。
$("div > div").filter(function() { return $(this).text() === "i"; });The filter method returns only elements that match the condition. The condition will only match elements whose text is the specified string.
Note that in your example, this will not match anything, as your selector div > div will select div elements that are direct children of another div, and the elements in your example have no parent div.
Here's an example of the code running. In the example, I've changed the selector to just div.
更多推荐
发布评论