2012-02-28 55 views
3

基於其HTML值的元素我有下面的標記: <ul class="list"> <li>4</li> <li>5</li> <li>6</li> </ul>選擇在jQuery的

如何選擇與5和6的HTML值的李項,並添加類呢?

+2

也許[此帖](HTTP:/ /stackoverflow.com/questions/1430290/jquery-select-based-on-text)會有幫助嗎? – Marshall 2012-02-28 17:55:17

回答

9

一種選擇是:contains selector ...

$("li:contains(5),li:contains(6)").addClass("myClassName"); 

然而,由於它只是尋找文字和不匹配的全部內容,這將還匹配<li>56</li>,<li>16</li>等。

所以,你或許應該做的,而不是爲使用.filter()像這樣:

$("li").filter(function() { 
    var text = $(this).text(); 
    return text === "5" || text === "6" 
}).addClass("myClassName"); 
+1

請注意,這也會選擇包含'56'或'5.1'的列表項或任何包含其中一個單一數字的列表項。 – Jasper 2012-02-28 17:58:28

+1

Aww,我得到了迴應。 – canon 2012-02-29 14:49:05

0
$("ul.list li").each(function(){ 
    if($(this).text() == '5' || $(this).text() == '6') { 
    $(this).addClass('theClass'); 
    } 
}); 
3

使用:contains()選擇

$("li:contains('5')") 
+0

這隻適用於只有單個數字的非常簡單的情況。 – wsanville 2012-02-28 18:01:19

+0

我不會投票,但你應該警告,這將匹配任何字符串或數字,其中有'5',如'50'或'5.0'。 – Jasper 2012-02-28 18:02:42

+0

我已經添加了原始文檔。 – 2012-02-28 18:04:19

4

您可以使用.filter()

//setup object of the characters we want to match (we will be matching the keys, not values) 
var whitelist = { 5 : 0, 6 : 0 }; 

//select all the list-item elements and filter them 
var $selectedElements = $('.list').children().filter(function() { 

    //returns true if the text of this element is one of the keys in the `whitelist` variable 
    return ($(this).text() in whitelist); 
}); 

如果返回true的元素將被保留在集的元素,如果你返回false,那麼它將被從集合中刪除。

這匹配元素的整個文本,它不僅檢查文本是否包含字符。

這裏是一個演示:http://jsfiddle.net/jasper/ndcFg/2/

0

我懷疑演示過於簡單化了......這是「價值」你的意思是文本

$('.list li').filter(function(){ 
    var txt=$(this).text(); 
    return txt==='4' || txt==='5';      
}).addClass('someclass');