如何使用JQuery获得包含完全包含指定文本的元素? [英] How can I get an element containing exactly the specified text using JQuery?

查看:414
本文介绍了如何使用JQuery获得包含完全包含指定文本的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,每个列表包含一个文本值.如何获得具有给定文本值的列表对象?

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>

上面的脚本为我提供了包含文本值i的所有div.如何解决此问题,以便获得与"i"具有完全相同的文本值的元素?

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是指定字符串的元素.

The filter method returns only elements that match the condition. The condition will only match elements whose text is the specified string.

请注意,在您的示例中,这将不匹配任何内容,因为选择器div > div将选择作为另一个div的直接子级的div元素,并且示例中的元素没有父级div.

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.

这是运行代码的示例.在示例中,我将选择器更改为div.

Here's an example of the code running. In the example, I've changed the selector to just div.

这篇关于如何使用JQuery获得包含完全包含指定文本的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆