如何使用jQuery根据单元格内容设置表的行类? [英] How to set the row class of a table based on cell content using jQuery?

查看:73
本文介绍了如何使用jQuery根据单元格内容设置表的行类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

<table class="grid">
    <thead>
        <tr>
            <th>Name</th>
            <th>Status</th>
        <tr>
    </thead>
    <tbody>
        <tr>
            <td>Project 1</td>
            <td>Closed</td>
        <tr>
        <tr>
            <td>Project 2</td>
            <td>Open</td>
        <tr>
        <tr>
            <td>Project 3</td>
            <td>Closed</td>
        <tr>
    </tbody>
</table>

我正在尝试将我在代码背后曾经做过的一些UI代码移动到jQuery.每当状态"(第2列)列的值为打开"时,我想更改TR元素的类.

I am trying to move some of my UI code that I used to do in the code-behind to jQuery. I would like to change the class of TR element whenever the Status (Column 2) column has a value of Open.

用jQuery做到这一点的最佳方法是什么?

What would be the best approach to doing this with jQuery?

推荐答案

$('tbody > tr', 'table.grid').filter(function() {
    return $(this).children('td').eq(1).text() == 'Open';
}).addClass('open_tr');

它在做什么:

它正在选择table.grid上下文的<tbody>内的所有<tr>元素.过滤器功能使您可以根据返回的内容过滤元素,保留则为true,否则为false.因此,在过滤器中,我们获得了tr的所有子代,获得了第二个<td>,并返回其文本是否等于'Open'-如果是,它将返回true,并且可以保留父<选择器中的c0>.剩下的只是<tr>处于打开"状态,因此我们可以添加一个类以将其标记为此类.

It is selecting all the <tr> elements inside the <tbody> of the table.grid context. The filter function allows you to filter elements based on what you return, either true to keep or false to discard. So inside the filter we get all the children of the tr, get the 2nd <td>, and return whether or not its text is equal to 'Open' - if it is, it would return true, and we could keep the parent <tr> in the selector. All that is left would then just be <tr> with Open status, so we can add a class to mark them as such.

这篇关于如何使用jQuery根据单元格内容设置表的行类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆