1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| HTML代码 <table width="200px" height="200px" border=" 1px" cellspacing='0'></table>
JS代码 let table = document.querySelector("table"); for (let i = 1; i <= 5; i++) { let tr = table.appendChild(document.createElement("tr")); for (let j= 1; j <= 5; j++) { 添加背景颜色的第一种写法 // i===j? tr.insertAdjacentHTML('beforeend',`<td style="background-color: red">${j}:${i}</td>`) : tr.insertAdjacentHTML('beforeend',`<td>${j}:${i}</td>`) 添加背景颜色的第二种写法 tr.insertAdjacentHTML('beforeend', `<td style=${i===j ? 'background-color:red' : ''}></td>`) } } 添加背景颜色的第三种写法 // for (let i = 0; i<table.rows.length; i++){ // table.rows[i].cells[i].style.backgroundColor="red"; // }
|