2011-08-16 22 views
1

我有一個問題,如果我想在任何頁面中使用jquery搜索一個perticular文本。我不想要的是如何搜索jquery中的文本?

<p id="1">iii</p> 
<p id="2">i</p> 
<p id="3">ibiib</p> 
<p id="4">bb</p> 
<p id="5">tina</p> 

<script type="text/javascript"> 
    console.log($("div:contains('i')")); 
</script> 

這上面的代碼給了我,除了ID = 4的所有段落;但我想要的只是選擇id = 2的段落。 如果有一種方法可以在javascript或任何其他庫中回答我的問題...

+0

你想要了解元素的全部內容嗎? –

+2

Exact duplicate:http://stackoverflow.com/questions/7076159/how-can-i-get-an-element-containing-exactly-the-specified-text-using-jquery/7076346#7076346 – Patrick

回答

1

可以擴展jQuery的選擇器引擎中添加一個新的:

$.expr[':'].texteq = function(elem, i, match, array) { 
    return $(elem).text() === match[3]; 
}; 

console.log($('p:texteq(i)')); 

Example

+0

非常好:)我將其稱爲':exact'(+1) – karim79

+0

@ karim79我想傳達它使用'$()。text'而不是'$()。html','$()。val'或其他任何東西。 –

4

使用$.filter

這將返回div s,其中只包含一個i

$('div').filter(function() { 
    return $(this).html() == 'i'; 
}); 
+0

謝謝你emill – teacher

3
$('p').filter(function() { 
    return $(this).text() === 'i'; 
}); 
+0

謝謝你joseph – teacher

+0

@frndsforever:如果一個答案已經解決了你的問題,點擊旁邊的複選標記來接受它,這樣其他人來這個帖子就會知道這是正確的答案。 –

1
$("p").each(function(a,b){ 
    if ($(this).html() == 'i'){ 
     console.log(a); 
    } 
}); 

$("p").filter(function(){ 
    return $(this).html() == 'i'; 
}); 
+0

什麼是需要通過a,b – teacher

+0

a是一個數字索引,它顯示你在哪裏找到「我」的地方 – genesis

1

您可以遍歷段落,並檢查他們的內容是一樣的你想要的內容。我使用了一個jQuery循環,如果你願意,你可以使用JavaScript。 JSFIDDLE

$('p').each(function() { 
    if(this.innerHTML == 'i') doWhateverYouWant(); 
}); 
1

我會用這一個簡單的插件:

$.fn.exactMatch = function(str) { 
    return this.filter(function() { 
     return $(this).text() === str; 
    }); 
}; 

$("p").exactMatch("i").css("border", "1px solid red"); 

You can try it here.