获取trs这个伪数组,对数组内元素用for循环判断操作。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title>
</head><body>
<table border="2" style="width: 400px; height: 300px;">
<tbody id="tb">
</tbody>
</table>
<script>
var tb = document.getElementById("tb");
setTable();
changeColor();
function setTable(){ var html = "";
for(var i = 0;i < 5;i++){
html += '<tr>'+
'<td>' + '</td>'+
'<td>' + '</td>'+
'<td>' + '</td>'+
'</tr>'; }
tb.innerHTML = html; }
function changeColor(){
var trs = document.querySelectorAll("tr");
for(var i = 0;i < trs.length;i+=2){
trs[i].style.backgroundColor = "red"; } }
</script>
</body><
/html>
来源:CSDN
作者:weixin_44064067
链接:https://blog.csdn.net/weixin_44064067/article/details/104740687