我有一个有 7 列的表格,每列代表一周中的 1 天。(链接到演示:https://jsfiddle.net/pL3dbfok/9/(
我希望列的背景随着页面加载而根据日期自动更改:如果是写在列上的日期,它的背景将变为灰色。(如果是星期六,星期六列将更改(。 我试过这个:
var d = new Date();
var n = d.getDay();
console.log(n)
if (n == 6) {
document.getElementById("SAT").style.backgroundColor = "gray";
} else {
document.getElementById("SAT").style.backgroundColor = "white";
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<table>
<tr>
<th id "SUN">Sunday</th>
<th id "MON">Monday</th>
<th id "TUE">Tuesday</th>
<th id "WED">Wednesday</th>
<th id "THU">Thursday</th>
<th id "FRI">Friday</th>
<th id "SAT">Saturday</th>
</tr>
</table>
当我将其设置为由按钮激活的功能时,它起作用了,但是当我尝试它不是在函数中时,希望它自动加载时,它不起作用。
我不熟悉js,所以这可能是我的一些愚蠢的错误。
如果可能的话,请使用js解决方案而不是jQuery进行响应。
您可以通过将行的cells
定位到适当的索引来简化此操作。
而不是使用内联样式,我还只会添加一个类并为背景和您想要的任何其他属性使用 css 规则
var d = new Date();
var n = d.getDay();
document.getElementById("heading-row").cells[n].classList.add('current-day');
.current-day{
background:grey
}
<table>
<tr id="heading-row">
<th>Sunday</th>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
</tr>
</table>
当您像此处一样直接调用脚本代码时,您的文档可能尚未完全加载,因此无法按 id 找到元素。 尝试在页面加载完成后运行代码,如下所示:
window.addEventListener('load', function()
{
var d = new Date();
var n = d.getDay();
console.log(n)
if (n == 6) {
document.getElementById("SAT").style.backgroundColor = "gray";
} else {
document.getElementById("SAT").style.backgroundColor = "white";
}
};
在 id 和它的值之间添加"="。
var d = new Date();
var n = d.getDay();
console.log(n)
if (n == 6) {
document.getElementById("SAT").style.backgroundColor = "gray";
} else {
document.getElementById("SAT").style.backgroundColor = "white";
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<table>
<tr>
<th id="SUN">Sunday</th>
<th id="MON">Monday</th>
<th id="TUE">Tuesday</th>
<th id="WED">Wednesday</th>
<th id="THU">Thursday</th>
<th id="FRI">Friday</th>
<th id="SAT">Saturday</th>
</tr>
</table>