【问题标题】:JQuery add class to row based on a valueJQuery根据值将类添加到行
【发布时间】:2020-05-13 17:42:24
【问题描述】:

我正在从 SQL Server 数据库中读取数据并以表格的形式显示它。但是,我需要有关如何根据使用 jquery 的属性之一的值向表中的行添加样式的帮助

列有这样的类

<td>
     <span class="funding-eligible">@Html.DisplayFor(modelItem => item.FundingEligibility)</span>
</td>

在 javascript 文件中我有这个

$(document).ready(function () {

    if ($(".funding-eligible").text() == 1) {
        $(".funding-eligible").addClass("eligible")
    }
});

【问题讨论】:

  • 只有一个元素具有“funding-eligible”类吗?

标签: javascript jquery asp.net asp.net-core


【解决方案1】:

循环通过funding-eligible.each() 然后使用closest() 获取父行

$(document).ready(function () {
    $(".funding-eligible").each(function(){            // .each to loop through elements 
       if(+$(this).text().trim() === 1){               // .trim() to avoid white-spaces , + here to covert the string to number
          $(this).closest('tr').addClass("eligible");  // .closest() to get the closest row
       }
    })
});

你也可以使用.filter()

$(document).ready(function () {
    $(".funding-eligible").filter(function(){  // .filter to filter elements by condition returned
       return +$(this).text().trim() === 1;    // .trim() to avoid white-spaces , + here to covert the string to number
    }).closest('tr').addClass("eligible");     // .closest() to get the closest row
});

但是.. 为什么在追加之前不使用条件将类添加到直接在 html 中的行中?类似&lt;tr class="&lt;?php echo ($eligible == 1) ? 'eligible' : '' ?&gt;"&gt;

【讨论】:

  • @Mohammed-Yousef 你是救世主!我整天都在试图弄清楚这一点。我还教过使用您建议的方法,但正在使用 Asp.Net Core,而且 DisplayFor 似乎不支持 htmlAttributes。与此同时,这很好用,但我仍然会尝试实施你建议的方法。非常感谢
  • 不客气@KaptinKoda .. 祝你有美好的一天:-)
猜你喜欢
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多