我需要能够动态更改表格行bg颜色,如下所示:
绿色,如果acc.Amount< acc.Balance
红色,如果acc.Amount> acc.Balance
无变化,如果acc.Amount == acc.Balance
<script type="text/javascript">
$(document).ready(function () {
$.ajax
({
type: "GET",
url: "/Account/Get/@ViewBag.AccountId",
dataType: 'json',
success: function(data) {
$.each(data, function (i, acc)
{
$('<tr>').append(
$('<td>').text(acc.Amount),
$('<td>').text(acc.Balance))
.appendTo('#myTable');
});
},
error: function() {
alert('Failed');
}
});
});
</script>
如何注入表格行bg颜色?
答案 0 :(得分:3)
我已更新您的脚本以包含逻辑以确定金额/余额相等,然后将内联样式或类(推荐)应用于表格行。
类方法需要您更新CSS。
<script type="text/javascript">
$(document).ready(function () {
$.ajax
({
type: "GET",
url: "/Account/Get/@ViewBag.AccountId",
dataType: 'json',
success: function(data) {
$.each(data, function (i, acc)
{
var amount = parseInt(acc.Amount, 10), // parse in case string
balance = parseInt(acc.Balance, 10), // parse in case string
color = amount < balance ? 'green' :
amount > balance ? 'red' :
'';
$('<tr>').append(
$('<td>').text(acc.Amount),
$('<td>').text(acc.Balance))
// I'm applying both an inline style and a class name
.css('background-color', color) // inline-style
.addClass(color) // adding class red/green
// continue code...
.appendTo('#myTable');
});
},
error: function() {
alert('Failed');
}
});
});
</script>