将类添加到包含具有特定值的列的表行

时间:2012-05-16 15:32:39

标签: jquery jquery-selectors matching

我需要在tr包含包含特定值的td时添加一个类。

使用this question on SO的答案,我认为我找到了解决方案,但它似乎不适用于包含多个列的行 - 只有在存在单个td时才有效。< / p>

如何识别包含具有特定值的列的表行以及其他列?请注意,列不会始终按特定顺序排列,因此它必须是动态答案。< / p>

The jsFiddle

<table>
    <tr>
        <td>Hey!</td>
        <td>Other column</td>
        <td>Yo!</td>
        <td>Other column2</td>        
    </tr>
</table>

<script type="text/javascript">
$('tr').each(function(){
 if (($(this).find('td').text() == 'Hey!' ) && ($(this).find('td').text() == 'Yo!' ))
 {
     alert('here');
     $(this).addClass('disabled');
 }
});
</script>

4 个答案:

答案 0 :(得分:1)

怎么样:

$('td:contains("Hey!"),td:contains("Yo!")').parent('tr').addClass('disabled');

或确保BOTH在那里

$('tr').each(function(){

    if($('td:contains("Hey!")').length > 0 && $('td:contains("Yo!")').length > 0)
        $(this).addClass('disabled');

});

答案 1 :(得分:1)

正如其他人所提到的,使用jQuery的:contains(text)选择器:

$('tr').each(function(){
   if($('td:contains("Hey!")', this).length && $('td:contains("Yo!")', this).length){       
        alert('here');
        $(this).addClass('disabled');
    }
});

类似的东西。

修改

更新了我使用length而不是jQuery的size()函数的答案。对那些发表证据支持使用length的观点更快的人表示赞赏。在对我自己做了一些基础研究之后,在jQuery文档中遇到了这个:

  

.size()方法在功能上等同于.length属性;   但是,.length属性是首选,因为它没有   函数调用的开销。

考虑到这一点,再加上下面的测试用例,我就卖掉了。想知道为什么size()甚至存在?我的想法是因为jQuery返回的某些对象不是数组,只有表现就像数组一样,并且考虑到使用size()更为可取。似乎后者至少不是这种情况。

干杯

答案 2 :(得分:0)

使用contains selector

$("td:contains('Hey!'), td:contains('Yo!')").each(function(){
   alert('here');
   $(this).parent().addClass('disabled');
});

答案 3 :(得分:0)

这是一个解决方案:

var search = ["Hey!", "Yo!"];

$("tr").filter(function() {
    var found = 0;
    $(this).children().each(function() {
        var text = $(this).text();
        for (var i = 0; i < search.length; i++) {
            if (text == search[i]) found++;
        }
    });
    return found == search.length;
}).addClass("disabled");​

DEMO: http://jsfiddle.net/Tnq9A/1/


如果你不需要文本的绝对重合而是部分,你可以使用这种比较方法:

if (text.indexOf(search[i]) != -1) found++;

DEMO: http://jsfiddle.net/Tnq9A/2/