如何设置表格中单元格的颜色出错



我正在验证表中的每个单元格,如果出现错误,我想将单元格涂成红色。这是我尝试过的(控制台上没有错误,当返回错误时,单元格不是红色的(:

css:

.redBg {background: red !important;}

javascript和jQuery:

//Return each element
var row = 0;
var column = 0;
$("#wrapper tr").each(function() {
row++;
column = 0;
if (row > 1) {
$('td', this).each(function() {
column++;
if (!$(this).text().replace(/s/g, '').length) {
alert("Row " + row + " column " + column + " only containes whitespace (i.e., empty, spaces, tabs or line breaks).");
} else {
if (column == 3) {
var dateFormat = 'DD/MM/YYYY';
if (!moment($(this).text(), dateFormat).isValid()) {
alert("Row " + row + " DOB does not contain a valid date.");
$('td', this).addClass('redBg');
}
}
if (column == 4) {
if (isNaN($(this).text())) {
alert("Row " + row + " Scout Number must be numeric. " + $(this).text());
$('td', this).addClass('redBg');
}
}
if (column == 5) {
var dateFormat = 'DD/MM/YYYY';
if (!moment($(this).text(), dateFormat).isValid()) {
alert("Row " + row + " Joining Date does not contain a valid date.");
$('td', this).addClass('redBg');
}
}
}
})
}
})

我也试过更换

$('td', this).addClass('redBg');

带有

$(this).find("td:nth-child(1)").css("background-color", red);

阅读moment.js关于严格解析的文档

从2.3.0版本开始,您可以为最后一个参数指定布尔值,以使Moment使用严格解析。严格的解析要求格式和输入完全匹配,包括delimeter。

moment('It is 2012-05-25', 'YYYY-MM-DD').isValid(); // true
moment('It is 2012-05-25', 'YYYY-MM-DD', true).isValid(); // false
moment('2012-05-25', 'YYYY-MM-DD', true).isValid(); // true
moment('2012.05.25', 'YYYY-MM-DD', true).isValid(); // false

此外,当$('td', this).each(函数内时,执行$('td', this)只是在TD内寻找TD,而不是您想要的。

此外,使用<tbody>'tbody'作为选择器(跳过剧院的TR(

此外,代替

if ( Boolean ) {
if ( Boolean ) {
}
}

你可以简单地做:

if(Boolean && Boolean) {
}

给你:

var dateFormat = 'DD/MM/YYYY'; // You need this set only once
$("#wrapper tbody tr").each(function() {
var row = $(this).index() + 1; // +1 since index is 0 based
$('td', this).each(function() {
var $col = $(this);
var col = $col.index() + 1;
var text = $.trim($col.text()); // GET TRIMMED TEXT
var err = ""; // Empty error
if (text.length === 0)
err += `Row ${row} column ${col} only containes whitespace (i.e., empty, spaces, tabs or line breaks).n`
if (col === 3 && !moment(text, dateFormat, true).isValid())
err += `Row ${row} DOB does not contain a valid date.`;
if (col === 4 && isNaN(text))
err += `Row ${row} Scout Number must be numeric. ${text}`;
if (col === 5 && !moment(text, dateFormat, true).isValid())
err += `Row ${row} Joining Date does not contain a valid date.`;
if (err) {
$(this).addClass('redBg');
alert(err);
}
});
});
.redBg {
background: red!important;
}
<table id="wrapper">
<thead>
<tr>
<th>#</th>
<th>?</th>
<th>DOB</th>
<th>Scout num.</th>
<th>Joined</th>
</tr>
</thead>
<tbody>
<td>#1</td>
<td>Joe</td>
<td>3</td>
<td>444</td>
<td>5</td>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

最新更新