gpt4 book ai didi

javascript - JQuery running contains on this variable/object

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:28 24 4
gpt4 key购买 nike

好吧,我对此很迷茫。首先,我使用 $this 获得对 jquery li 对象的引用,然后我尝试使用“包含”jquery 函数在该 li 中搜索是否存在某些文本。但是带有“包含”的行永远不会返回 true。

$("ul li").each(function(index) {
var $this = $(this);

//Attempt 1 using $this
if ($this.is(":contains('some text' ) ")) {
console.log(" matching free text found");
} else {
console.log(" matching free text not found");
}
//Attempt 2 using $(this)
if ($(this).is(":contains('some text' ) ")) {
console.log(" matching free text found");
} else {
console.log(" matching free text not found");
}


})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
<li>one</li>
<li>two</li>
<li>some text here</li>
</ul>

最佳答案

您只需从 :contains(some text) 中删除 ' '。

jQuery 文档: jQuery - contains selector

$("ul li").each(function(index) {
var $this = $(this);

//Attempt 1 using $this
if ($this.is(":contains(some text) ")) {
console.log(" matching free text found at Index: " + index);
} else {
console.log(" matching free text not found");
}
//Attempt 2 using $(this)
if ($(this).is(":contains(some text ) ")) {
console.log(" matching free text found at index: " + index);
} else {
console.log(" matching free text not found");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>one</li>
<li>two</li>
<li>some text here</li>
</ul>

关于javascript - JQuery running contains on this variable/object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543473/

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