我已编写此代码,但我不知道在单击按钮时如何重置棋盘。当我单击按钮时,棋盘会一次又一次地生成。我不知道如何解决这个问题。
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Chessboard</title>
<link rel="stylesheet" sype="text/css" href = "chessboard.css">
<script src="chessboard.js"></script>
</head>
<body>
<button onclick="fn()">Display</button>
<p></p>
<div id="chessBoard"></div>
</body>
</html>
JavaScript的:
function fn() {
var x=8;
var y=8;
var chessBoard = document.getElementById("chessBoard");
for (var i=0; i<y; i++){
var row = chessBoard.appendChild(document.createElement("div"));
for (var j=0; j<x; j++){
row.appendChild(document.createElement("span"));
}
}
}
CSS:
#chessBoard {
display: inline-block;
}
#chessBoard div {
line-height: 1px;
}
#chessBoard span {
display: inline-block;
width: 32px;
height: 32px;
}
#chessBoard div:nth-child(odd) span:nth-child(even),
#chessBoard div:nth-child(even) span:nth-child(odd){
background-color: black;
}
#chessBoard div:nth-child(even) span:nth-child(even),
#chessBoard div:nth-child(odd) span:nth-child(odd){
background-color: snow;
}
答案 0 :(得分:0)
可能太巧妙了,但是在重新创建第二块板之前,它应该删除div棋盘的内容。
function fn() {
var x=8;
var y=8;
var chessBoard = document.getElementById("chessBoard");
chessBoard.innerHTML = "";
for (var i=0; i<y; i++){
var row = chessBoard.appendChild(document.createElement("div"));
for (var j=0; j<x; j++){
row.appendChild(document.createElement("span"));
}
}
}
答案 1 :(得分:0)
正如@MarcB所说,你需要在重新绘制之前清理原始的主板。 在代码中添加while循环即可。
function fn()
{
var x=8;
var y=8;
var chessBoard = document.getElementById("chessBoard");
while(chessBoard.children.length > 0)
{
chessBoard.removeChild(chessBoard.childNodes[0]);
}
for (var i=0; i<y; i++)
{
var row = chessBoard.appendChild(document.createElement("div"));
for (var j=0; j<x; j++)
{
row.appendChild(document.createElement("span"));
}
}
}