jQuery - 如果body包含完全字符串,则make变量为true

时间:2016-07-14 14:19:10

标签: javascript jquery

我的页面上有这两个元素。

<p>Some text<p>
<p>Some text that I need</p>

如果有包含确切文字的文字&#34;我需要的一些文字&#34;那么我希望我的变量测试是真的。如果不是那么必须是假的。因此,如果页面仅包含某些文本,需要或那些,那么必须是变量false。

我的代码不起作用,为什么?

var test = $("body").filter(function() {
    return $(this).text() === "Some text that I need" ? true : false;
})

3 个答案:

答案 0 :(得分:2)

有两个问题。首先,您应该使用p选择$("p")元素。

但是.filter将始终返回jQuery结果集,如果不匹配,则它将是一个空结果集,因此您需要使用.length测试结果集中是否存在元素。

var test = $("p").filter(function() {
    return $(this).text().trim() === "Some text that I need";
}).length > 0;

编辑添加了.trim,以便它也匹配<p> Some text that I need </p>

根据您的评论 This text should once in p element, once in span sometimes in li element.

您需要选择文档中的所有元素:

var test = $("body *").filter(function() {
    return $(this).text().trim() === "Some text that I need";
}).length > 0;

答案 1 :(得分:1)

试试这个:

var test = $("body *").filter(function() {
    return $(this).text() === "Some text that I need" ? true : false;
}).length > 0;

JSFiddle

答案 2 :(得分:1)

这样做的一个简单示例是:

我在这里使用.each()

$("body *").each() //will handle any child containing the text you are looking for

$("body p").each() //will handle any p tag containing the text you are looking for

$("body p, body li").each() //will handle any p or li tag containing the text you are looking for

var test = false;
var searchText = "Some text that I need";
$("body *").each(function() { //will handle any child containing the text you are looking for
  if ($(this).text().trim() === searchText) {
    test = true;
    return;
  }
});
console.log(test);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Some text</p>
<p>Some text that I need</p>
<span>Some text that I need</span>