gpt4 book ai didi

javascript - 如何重新加载由javascript创建的表

转载 作者:行者123 更新时间:2023-11-28 04:55:16 25 4
gpt4 key购买 nike

我通过 for 循环创建一个 n*n 表,然后更改 n 的值并想要重新加载表以显示新表。

 <table id = "chessboard">
<script>
createChessboard()
</script>
</table>

JavaScript:

function createChessboard() {
document.write('<tr><td></td>')
for (var column=0;column<size;column++){
document.write("<td>"+(column+1)+"</td>")
}
document.write('</tr>')
for(var row=0;row<size;row++){
document.write("<tr>")
document.write("<td>"+(row+1)+"</td>")
for(var column=0;column<size;column++){
if(column%2 == row%2){
document.write("<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:#E5E4E2'/>")
}else {
document.write("<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:gray'/>")
}

}
document.write("</tr>")
}
}

如何在 onchange() 方法中执行此操作?

最佳答案

我刚刚替换了 document.write 因为它是 bad practice 。因此,每次更改 select 时,都会绘制表 DOM 元素。

function createChessboard(size) {
var innerHTML = '<tr><td></td>';
for (var column=0;column<size;column++){
innerHTML += "<td>"+(column+1)+"</td>";
}

innerHTML += '</tr>';
for(var row=0;row<size;row++){
innerHTML += "<tr>";
innerHTML += "<td>"+(row+1)+"</td>";
for(var column=0;column<size;column++){
if(column%2 == row%2){
innerHTML += "<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:#E5E4E2'/>";
} else {
innerHTML += "<td><input id="+row+column+" type=button onclick='putQueen(id)' style='background:gray'/>";
}
}

innerHTML += "</tr>";
}

var chessEl = document.querySelector('#chessboard');
chessEl.innerHTML = innerHTML;
};

createChessboard(5);

function changeSize(el) {
var val = el.options[el.selectedIndex].value;
createChessboard(val);
}
  <form>
<select onchange="changeSize(this)" >
<option value="5"> 5 </option>
<option value="8"> 8 </option>
</select>
</form>

<table id ="chessboard">
</table>

关于javascript - 如何重新加载由javascript创建的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42598117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com