gpt4 book ai didi

jquery - 我怎样才能直接定位有文本的元素,而不是它们的父元素?

转载 作者:行者123 更新时间:2023-11-28 03:52:29 24 4
gpt4 key购买 nike

我想选择包含文本的元素,而不考虑它们的类型。我不想选择他们的后代。我试过这个$(":contains('Twilight')").css('border-left', '1px solid purple');但这会选择带有文本 的元素,它是 dom 树上的祖先元素。

下面是一些 HTML 示例。我想选择标有 <!-- THIS --> 的那些, 没有其他的。我该怎么做?

<div>                                       <!-- no -->
<h1>Magical ponies</h1> <!-- no -->
<ul> <!-- no -->
<li>Fluttershy</li> <!-- no -->
<li>Pinkie pie</li> <!-- no -->
<li>Twilight sparkle</li> <!-- THIS -->
<li>Hurdurrdurr</li> <!-- no -->
</ul>
</div>
<div>Twilight is a movie too</div> <!-- THIS -->
<p>Hurr <!-- no -->
<span>Twilight ZONE</span> <!-- THIS -->
Durr</p>

这是一个可以玩的 jsfiddle:http://jsfiddle.net/34C7Z/ - 我特别希望解决方案是 jquery 而不是原生 JS。

最佳答案

我看到的唯一解决方案:

$("*").filter(function(){
return $(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text() //get the text
.indexOf("Twilight") >= 0;
}).css('border-left', '1px solid purple');

我从这里获取了过滤器函数体:Using .text() to retrieve only text not nested in child tags

问题是 contains 选择器使用 text 返回的 jQuery 函数接受元素后面的所有内容并剥离 html 标签。这就是为什么您必须以编程方式执行此操作的原因,jQuery 没有函数或选择器只返回不在嵌套子项中的文本。

您应该更改开头的 $("*") 选择器。

关于jquery - 我怎样才能直接定位有文本的元素,而不是它们的父元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com