我想创建一个on on按钮来运行一个javascript函数来生成一个填字游戏风格的网格。
我已经编写了一些javascript来创建网格,我已经使用onclick函数创建了按钮,但是我无法获得运行脚本的按钮。
我确信这个解决方案非常明显,但我是编码的新手,所以任何和所有的帮助都会受到赞赏!
<html>
<body>
<!--<button onclick="generateGrid()">Click to generate crossword grid</button>-->
<div id="crosswordGrid" align="center"></div>
</body>
</html>
function generateGrid () {
var crosswordGrid = document.getElementById("crosswordGrid");
for (var r = 0; r < rows; r++) {
var row = crosswordGrid.appendChild(document.createElement("div"));
for (var c = 0; c < cols; c++) {
row.appendChild(document.createElement("span"));
}
}
const gridSize = 7;
var rows = gridSize;
var cols = gridSize;
}
这是我目前的代码; http://jsfiddle.net/YEJ9A/97/
答案 0 :(得分:1)
所以我认为你主要是那里的方式。我将您在文件底部指定的值移动到函数的默认值。请参阅下面的更正。
还在小提琴上更新。 https://jsfiddle.net/r8aLbakr/1/
function generateGrid (gridSize = 7, rows = 7, cols = 7, crosswordGrid) {
var crosswordGrid = document.getElementById("crosswordGrid");
for (var r = 0; r < rows; r++) {
var row = crosswordGrid.appendChild(document.createElement("div"));
for (var c = 0; c < cols; c++) {
row.appendChild(document.createElement("span"));
}
}
}
#crosswordGrid div {
line-height: 1px;
}
#crosswordGrid span {
display: inline-block;
width: 28px;
height: 28px;
border: 1px solid black;
}
#crosswordGrid div:nth-child(even) span:nth-child(even) {
background-color: black;
}
#crosswordGrid div:nth-child(odd) span:nth-child(odd) {
background-color: white;
}
<html>
<body>
<button onclick="generateGrid()">Click to generate crossword grid</button>
<div id="crosswordGrid" align="center"></div>
</body>
</html>
答案 1 :(得分:1)
尝试使用“addEventListener”而不是“onclick”
这是我的回答
document.getElementById ("btn").addEventListener("click", function() {
generateGrid(7);
} , false);
function generateGrid(gridSize) {
var rows = gridSize;
var cols = gridSize;
var crosswordGrid = document.getElementById("crosswordGrid");
for (var r = 0; r < rows; r++) {
var row = crosswordGrid.appendChild(document.createElement("div"));
for (var c = 0; c < cols; c++) {
row.appendChild(document.createElement("span"));
}
}
}
#crosswordGrid div {
line-height: 1px;
}
#crosswordGrid span {
display: inline-block;
width: 28px;
height: 28px;
border: 1px solid black;
}
#crosswordGrid div:nth-child(even) span:nth-child(even) {
background-color: black;
}
#crosswordGrid div:nth-child(odd) span:nth-child(odd) {
background-color: white;
}
<html>
<body>
<button id="btn">Click to generate crossword grid</button>
<div id="crosswordGrid" align="center"></div>
</body>
</html>