2014-09-20 23 views
0

我想使用jquery在.sos單元格中搜索文本範圍並根據範圍集的值更改bg顏色。按範圍,我的意思是每個#1-6的單數實例,如果文本完全包含數字1,2,3,4,5或6。jQuery篩選文本範圍並應用新的bg顏色

text value 1-6 = green 
text value 7-12 = blue 
text value 13-20 = yellow 
text value 21-26 = pink 
text value 21-26 = black 
then also if no text value matched set a different color or purple 

例如HTML

<td class="sos">11</td> 
<td class="sos">2</td> 
<td class="sos">32</td> 
<td class="sos">3</td> 

我知道該怎麼做一次每個文本值1,但還沒有看到任何TUTS做一個範圍,如果可能的話。

$('.sos').each(function() { 
    if ($(this).text() == '3') { 
     $(this).css('background', 'red'); 
    } 
}); 
+0

你所說的 「範圍」 是什麼意思?請舉個例子。 – loveNoHate 2014-09-20 11:10:41

+0

我給出了上述範圍,如果td.sos包含文本1-6(1,2,3,4,5或6),然後應用bg顏色的綠色 – MShack 2014-09-20 11:12:39

+0

$('。sos')。each(function(如果($(this).text()> = 2 && $(this).text()<= 7){ }(this).css('background','red'); } }); – 2014-09-20 11:14:15

回答

1

分配IDHTML Table並沒有必要指定類各td

HTML

<table id="tableID"> 
<tr> 
    <td>11</td> 
    <td>2</td> 
    <td>32</td> 
    <td>3</td> 
</tr> 
</table> 

jQuery的

$("#tableID td").each(function() { 
    var a = $(this).text(); 
    if(parseInt(a)>=1 && parseInt(a)<=6) 
    { 
    $(this).css('background', 'red'); 
    } 
    //... AND so on for other conditions 
}); 

OR

$("#tableID td").each(function() {  
    (parseInt($(this).text()) >= 1 && parseInt($(this).text()) <= 6 ? 
    $(this).css('background', 'red') : "") 
}); 

DEMO