根据表格单元格值更改行的颜色

问题描述 投票:1回答:3

如果单元格包含该行内的某些文本,我试图更改表格行的颜色。例如,如果单元格的值为Failed,则行将变为红色。但只有一行按其应有的方式发挥作用。

这是我的代码。

CSS:

<style>    
   .failed {
       background: red !important;
       color: white !important;
   }
</style>

HTML:

<table class="table table-striped">
    <thead>
        <tr>
            <th class="text-center">#</th>
            <th>Session Eamil</th>
            <th>Login Url</th>
            <th>Date</th>
            <th>Status</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @{ var counter = 1;}
            @foreach (var item in Model)
            {
                <tr>
                    <td class="text-center">@counter</td>
                    <td>@item.SessionEmail</td>
                    <td>@item.LoginUrl</td>
                    <td>@item.CreatedAt.ToLocalTime().ToString("G")</td>
                    <td>@item.Status</td>
                    <td class="text-center">
                        <a href='@Url.Action("JobDetail","ArchivedScrapeJob", new{jobId=item.Id})'><span class="glyphicon glyphicon-option-horizontal" aria-hidden="true"></span></a>
                    </td>
                </tr>
        counter++;
            }
    </tbody>
</table>

JS代码:

<script>
    $(function() {

        $(".table-striped").find("tr").each(function () {
            $("td").filter(function() {
                return $(this).text() === "Failed";
            }).parent().addClass("failed");
        });
    });
</script>

我想要完成的是如果失败则根据td值更改行颜色。查看实际输出:Actual Output

解决了

jquery html css asp.net
3个回答
1
投票

无需编写任何js代码。您可以直接在tr标签上添加状态类

<tr class='@item.Status'>

.Failed {
    background: red;
    color: white;
}

4
投票

为什么不直接在剃刀代码中设置类?

<tr class="@(item.Status == "Failed" ? "failed" : "")">

1
投票

在州列中添加一个类

<td class="status">@item.Status</td>

然后在脚本中:

<script>
    $(function() {

        $(".table-striped").find("tr").each(function () {
           var status= $(this).find(".status").html();  
           if(status=="Failed")
             {
                    $(this).addClass("failed")
             }
        });
    });
</script>

它会工作。试试吧 !

© www.soinside.com 2019 - 2024. All rights reserved.