我正在尝试做一个 eclipse 刻素描游戏。我几乎完成了,有一个清除按钮,一个随机网格生成器按钮,和一个输入字段,使一个NxN网格。我把这2个按钮和输入字段放进一个表单,输入字段就不再工作了。清除按钮和随机网格生成器仍然工作。我把它们都移到同一个表单中,用CSS来设计它们的样式,如果可能的话,我想把它们留在表单中。我不明白为什么我的输入字段不再工作,但其他一切都可以。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="JS.js" defer></script>
<title>Document</title>
</head>
<body>
<div class="header">
<h1>Etch A Sketch</h1>
<form id="inputForm">
<button id="clear">Clear</button>
<button id="generator">Random Grid</button>
<input type="number" id="number" min=1 max=64 placeholder="Enter a # 1-64">
</form>
</div>
<div id="gridContainer">
</div>
</body>
</html>
//Grabs the form where are of this is housed
var form = document.getElementById("inputForm");
var clearButton = document.getElementById("clear");
var input = document.getElementById("number");
//Starts function that does everything
form.addEventListener("submit", function(e) {
//Prevents browser from refreshing on submit
e.preventDefault();
input.disabled = true;
var boxInput = input.value;
var gridContainer = document.getElementById("gridContainer");
console.log(boxInput);
for (var i = 0; i <= boxInput * boxInput - 1; i++) {
//Creates a certain number of rows and columns based on user input
gridContainer.style.gridTemplateColumns = `repeat(${boxInput}, 1fr)`;
gridContainer.style.gridTemplateRows = `repeat(${boxInput}, 1fr)`;
var div = document.createElement("div");
console.log(div);
div.className = "grid";
gridContainer.appendChild(div);
}
});
//If you click on random grid it will create a grid between 1-64
var randomGrid = document.getElementById('generator')
randomGrid.addEventListener('click', function(){
var randomNumber = Math.floor(Math.random() * (65 - 1) + 1);
console.log(randomNumber);
for (var i = 0; i <= randomNumber * randomNumber - 1; i++) {
gridContainer.style.gridTemplateColumns = `repeat(${randomNumber}, 1fr)`;
gridContainer.style.gridTemplateRows = `repeat(${randomNumber}, 1fr)`;
var div = document.createElement("div");
console.log(div);
div.className = "grid";
gridContainer.appendChild(div);
input.disabled = true;
}
});
//Makes it blue if you mouseover
gridContainer.addEventListener('mouseover', function(element) {
if (element.target.classList.contains('grid')) {
element.target.style.backgroundColor = 'black';
}
});
//Clears grid when clicked on
clearButton.addEventListener("click", function(e) {
e.preventDefault();
input.disabled = false;
input.value = '';
var divs = gridContainer.getElementsByClassName('grid');
while (divs.length > 0) {
gridContainer.removeChild(divs[0]);
}
});
2条答案
按热度按时间8ftvxx2r1#
您需要在button元素中指定type属性,因为它位于form元素中。
因为没有指定type,所以默认情况下它调用form的onsubmit方法。Mozilla Docs说
formmethod...
如果该按钮是一个提交按钮(它在
<form>
内/与<form>
关联,并且没有type="button"
),则该属性指定用于提交表单的HTTP方法。um6iljoc2#
实际上你不需要表单,只需要听输入