2010-09-22 76 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