2010-09-22 70 views
0

我正在嘗試將css規則應用於tr元素,具體取決於哪些類將是以下tr。jquery if語句檢測是否存在具有「X」類的tr

ex。

<table> 
<tr class="x"/> 
<tr class="y"/> 
<tr class="x"/> 
<tr class="x"/> 
</table> 

因此,與類X具有與Y類跟隨TR將具有比TR,未來TR是X類不同的CSS樣式的TR。

<script type="text/javascript"> 
$(document).ready(function() { 
    if ($("tr.x").next('(tr.y)')) { 

     $(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'}); 

     } 
    else{ 

     $(this).css({'background-color' : 'blue', 'font-weight' : 'normal'}); 

     } 
}); 
</script> 

它根本不工作,我不知道爲什麼。

任何幫助,將不勝感激。

在此先感謝。

更新

我想的CSS樣式應用到TR的第一個TD,我試圖;

$(this).first('td').css({ 'color': 'Blue',}); 

但仍然適用於行。

再次感謝所有。

回答

2

我更新的答案被Sarfraz's original answer啓發,但他在去年底以不同的方式,所以在這裏發帖來代替:

$('tr.x:has(+ tr.y)').css({ ... }); 

一個使用sibling combinator:has測試。 (我不確定是否:has是一個Sizzle特定的事情[Sizzle是jQuery和其他人使用的選擇器引擎)還是有一個提案;它不是由CSS3指定的,所以不是標準的......但是?)

活生生的例子:http://jsbin.com/imeso4/3

更新如果你想將樣式應用到第一子細胞該行的,你要尋找的:first-child選擇:

$('tr.x:has(+ tr.y) td:first-child').css({ ... }); 

直播例如:http://jsbin.com/imeso4/8

或者如果你想對行做些什麼,然後做一些事情與細胞納克,打破它:

var rows = $('tr.x:has(+ tr.y)'); 
rows.css({color: 'blue'}); 
rows.find('td:first-child').css({color: 'red'}); 

活生生的例子:http://jsbin.com/imeso4/7


原件(單調乏味)答案:

$(document).ready(function() { 

    $('tr.x').each(function() { 
     var $this = $(this); 
     var next = $this.next('tr'); 
     if (next.length > 0 && next.hasClass('y')) { 
      // This tr is class x followed by class y 
     } 
    }); 

}); 

活生生的例子:http://jsbin.com/imeso4

+0

我想將CSS樣式應用於tr的第一個td,而我正在嘗試; (this).first('td')。css({'color':'Blue',}); 但仍然適用於行 – Amra 2010-09-22 11:38:49

+0

@Cesar:您正在尋找'td:first-child',我已經更新了答案。 – 2010-09-22 13:26:33

+0

@ T.J。克勞德:感謝你的回覆,我想我沒有很好地解釋自己,我需要將風格應用到每個通過條件的tr的第一個td。再次感謝。 – Amra 2010-09-22 13:45:27

4

試試這個:

$('.x + .y').prev().css({'background-color' : 'yellow', 'font-weight' : 'bolder'}); 

Working Demo

+1

這將風格的.y元素,而不是.x元素。 – 2010-09-22 10:17:44

+0

@Sarfraz:我冒昧地爲你更新它。 – 2010-09-22 10:21:29

+0

@Sarfaz:啊,重疊的編輯,你用一個不同的,但也是工作的例子來消滅我。 – 2010-09-22 10:23:17

1

你應該拆分這分成兩個:jQuery和CSS。使用CSS來設置所有的.x元素,並使用jQuery來進行特殊的格式設置。

$(".y").prev(".x").children("td").first().css({'background-color':'yellow', 'font-weight':'bolder'}); 

演示:http://jsbin.com/enova4

編輯:其實,你應該只添加一個類你的 「特殊」 .X元素,並在CSS中執行所有的造型。我還調整了代碼以解決第一個孩子td。

$(".y").prev(".x").children("td").first().addClass('x-special'); 

... 
<style> 
.x-special { 
    background-color: yellow; 
    font-weight: bolder; 
} 
</style> 
+0

謝謝你的回答,目前它只適用於第一行的第一個td,我需要它爲第一個td完成行。 – Amra 2010-09-22 13:05:57

+0

好點 - 使用兒童(「td:first-child」)而不是兒童(「td」)。first()應該做到這一點:) – 2010-09-22 14:05:35