2016-07-14 47 views
1

我已經在我的頁面上這兩個元素。jQuery - 如果body包含確切的字符串,然後使變量爲true

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

如果有確切的文字文本「一些文字,我需要」,那麼我想我的變量測試是真實的。如果不是,那麼一定是假的。所以如果頁面只包含一些文本,需要或者那個,那麼必須是變量false。

我的代碼不工作,爲什麼?

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

「這」 指的是身體標記。 – jordaniac89

+0

$(這個)在這方面是身體標籤... – Liam

+0

身體是**從不**會包含'我需要的某些文字'因爲它包含'

我需要的一些文字

'。目前還不清楚你想如何運作? – Liam

回答

1

試試這個:

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

JSFiddle

+0

@dfsq OP詢問主體何時包含具有特定文本的元素,他希望'test'爲真,對嗎? –

+0

對,但這並不意味着這段文字是身體的直接子女。無論如何,它可能對OP有用。乾杯!順便說一句,OP要布爾結果,長度是一個數字,所以可能'長度> 0'。 – dfsq

+0

@dfsq好的,我明白你的意思,謝謝! –

2

有兩個問題。首先,您應該使用$("p")選擇p元素。

.filter將始終返回一個jQuery結果集,如果不匹配,它將是一個空結果集,因此您需要測試結果集中是否存在使用.length的元素。

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

編輯添加.trim因此,它也將基於您的評論 This text should once in p element, once in span sometimes in li element.匹配<p> Some text that I need </p>

您需要選擇文檔中的所有元素:

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

@dfsq thats true。 –

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>

相關問題