我有一个页面,上面有几个具有相同类名的表。我想交替此页面上每个表的行的颜色。我将下面的代码与 . 此代码无法正常工作,因为一次只有 1 个表格(第一个表格)交替颜色。我究竟做错了什么?我页面上的所有表格都有“mytable”类。
function altrows(classname,firstcolor,secondcolor)
{
var tableElements = document.getElementsByClassName(classname) ;
for(var j= 0; j < tableElements.length; j++)
{
var table = tableElements[j] ;
var rows = table.getElementsByTagName("tr") ;
for(var i = 0; i < rows.length; i=i+2)
{
rows[i].bgColor = firstcolor ;
rows[i+1].bgColor = secondcolor ;
}
}
}
Run Code Online (Sandbox Code Playgroud)
rows[i]永远存在,但也rows[i + 1]可能不存在。然后rows[i+1].bgColor = secondcolor ;导致某种致命错误,破坏整个脚本。
考虑使用 CSS:
table tr:nth-child(even) {
background-color: red;
}
table tr:nth-child(odd) {
background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)或者使用固定的JS:
函数 altrows(classname,firstcolor,secondcolor) { var tableElements = document.getElementsByClassName(classname) ;
for(var j = 0; j < tableElements.length; j++)
{
var table = tableElements[j] ;
var rows = table.getElementsByTagName("tr") ;
for(var i = 0; i < rows.length; i++)
{
rows[i].bgColor = i % 2 == 0 ? firstcolor : secondcolor ;
}
}
Run Code Online (Sandbox Code Playgroud)
}