我有一个带有单元格的表,并希望将每个单元格的背景设置移动到JavaScript中。怎么做呢?现在我无法到达函数color1
<head>
<script language="JavaScript">
function color1(row, col){
if(isOdd(row) && isOdd(col)) return "#f4cd8d";
if(isEven(row) && isEven(col)) return "#745853";
}
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
</script>
</head>
<body>
<table id="chessboard" border="1" cellspacing="0" cellpadding="0">
<tr height="30"
th:each="row, rStat : ${#numbers.sequence(1, 8)}">
<td width="30" th:each="col, cStat : ${#numbers.sequence(1, 8)}"
th:data-row=${rStat.count}
th:data-col=${cStat.count}
th:style="'background: onload="javascript:color1(${rStat.count},${cStat.count})";'">
</td>
</tr>
</table>
</body>
尝试这样调用JavaScript:
<table id="chessboard" border="1" cellspacing="0" cellpadding="0">
<tr height="30"
th:each="row, rStat : ${#numbers.sequence(1, 8)}">
<td th:id="${id}" width="30" th:each="col, cStat : ${#numbers.sequence(1, 8)}"
th:data-row=${rStat.count}
th:data-col=${cStat.count}
th:attr="onload='color1(${rStat.count},${cStat.count})'">
</td>
</tr>
</table>
在javascript中你可以设置字段
的样式function color1(row, col){
var cell = document.querySelector('#id');
var color;
if(isOdd(row) && isOdd(col)) color = "#f4cd8d";
if(isEven(row) && isEven(col)) color = "#745853";
cell.style.background = color;
}
既然你已经在使用JQuery,为什么不使用document.ready()来分配这样的颜色?不需要在表本身上使用任何JavaScript。
<script>
$(document).ready(function () {
$('.chessboard-square').each(function () {
let row = parseInt($(this).data('row'));
let col = parseInt($(this).data('col'));
$(this).css('background-color', color1(row, col));
})
});
</script>
<!-- Table -->
<table id="chessboard" border="1" cellspacing="0" cellpadding="0">
<tr height="30" th:each="row, rStat : ${#numbers.sequence(1, 8)}">
<td class="chessboard-square" width="30" th:each="col, cStat : ${#numbers.sequence(1, 8)}"
th:data-row="${rStat.count}"
th:data-col="${cStat.count}">
</td>
</tr>
</table>