JQuery 运行包含此变量/对象



好吧,我对此很迷茫。 首先,我使用 $this 获取对 jquery li 对象的引用,然后我尝试使用 "contains" 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(一些文本(中删除 ' '。

j查询文档: jQuery - 包含选择器

$("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>

我对jQuery了解不多(因为我几年前放弃使用它而支持ES6(,但这很容易使用vanilla Javascript来实现。

document.querySelectorAll("ul li").forEach(function(li) {
console.log(`matching free text${li.textContent.includes('some 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>

使用$(this).text()获取li的当前文本,String.includes(text)检查字符串中是否存在文本。

$("ul li").each(function(index) {
var _this = $(this);
//Attempt 1 using $this
if (_this.text().includes('some text'))) {
console.log("matching free text found");
} else {
console.log("matching free text not found");
}
})