这个想法是,当单击按钮时,它将生成与单击次数一样多的框(例如:20 次单击 = 页面上的 20 个框)但是,我需要它,当您单击该框时会弹出一个唯一 ID 的警报. 我不确定如何为每个盒子分配一个唯一的 ID ...
这是HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>E02W03_Q2</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="E03_Q2.css">
<script src="E03_Q2.js"></script>
</head>
<body>
<form>
<input type="button" id="addButton" value="Add Box">
</form>
<div class="clrBox">
</div>
</body>
</html>
CSS 代码:
.clrBox {
background-color: red;
width: 50px;
height: 50px;
margin: 10px;
}
JavaScript 代码:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
var box = document.getElementByTagName("div");
button.onclick = handleButtonClick;
box.onclick = handelBoxClick;
}
function handleButtonClick(e) {
var div = document.createElement("div");
div.setAttribute("class","clrBox");
var body = document.getElementsByTagName("body");
body[0].appendChild(div);
}
function handelBoxClick(e){ <<This isnt quite finished yet since i'm not sure of how to assign each box a unique id...
var div = document.getElementById("");
alert();
}