2012-08-06 32 views
0

我目前有一個表,它是我的數據庫結果中的while循環。在我的表格行中,它包含的值將是+或 - 天數。我試圖創建一個jQuery腳本,它將查明td是否包含(「 - 」)或(「+」),並且我希望它將css樣式應用於該行的第一個td。目前它適用於全部行的每個第一個td。如何讓jQuery將類應用到連續的第一個td

 $("tr td:nth-child(7):contains('+')").each(function() { 
    $('tr td:first-child').css('background-color', 'blue'); 
    }); 

回答

2

您需要使用$(this),以便您引用循環中的「this」元素。

然後,因爲「this」是td元素,請找到父代tr,然後找到嵌套在該元素中的first-child

$("tr td:nth-child(7):contains('+')").each(function() { 
    $(this).parent("tr").find('td:first-child').css('background-color', 'blue'); 
}); 

見演示:http://jsfiddle.net/g7ZTf/

+0

由於這個工作。 – TheGambit 2012-08-06 10:05:59

+0

@TheGambit沒問題,如果這對你有幫助,請接受答案。 http://meta.stackexchange.com/a/5235/151209 – Curt 2012-08-06 10:51:07

1

我會做這樣的...

$(function(){ 
    $("tr td:nth-child(7):contains('+')").each(function() { 
     // get a jQuery object of the selected element using `$(this)` 
     // then select `.siblings()`, and limit to first element in array (`.eq(0)`) 
     $(this).siblings().eq(0).css('background-color', 'blue'); 
    }); 
});​ 

小提琴:http://jsfiddle.net/FqUB3/

+0

+1替代方法 – Curt 2012-08-06 10:11:41

相關問題