如何使用JQuery获取包含指定文本的元素?(How can I get an element containing exactly the specified text using JQuery?)

系统教程 行业动态 更新时间:2024-06-14 16:57:40
如何使用JQuery获取包含指定文本的元素?(How can I get an element containing exactly the specified text using JQuery?)

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

<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.

更多推荐

本文发布于:2023-04-13 12:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/a63771ccac1fe1d16e5a52fb92e25ec2.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   元素   文本   text   JQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!