[英]How to Remove anonymous function from DOM elements
我正在嘗試用 javascript 創建一個迷你猜謎游戲。 所以基本上,第一次一切正常,但第二次我開始遇到一些問題,這些項目仍然具有以前的狀態。 我試圖刪除 function 但我不知道如何
<div class="container">
<div class="item" >box1</div>
<div class="item" >box2</div>
<div class="item" >box3</div>
<button onclick="startGame()">START</button>
</div>
<h1 id="score" style="text-align: center;"></h1>
這是我的 javascript
var score =0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
function startGame() {
alert("game started !!! chose a box")
var luckNum = getRandomInt(0, 2)
console.log("this is lucky Num " + luckNum)
let item = [...document.getElementsByClassName("item")]
item.forEach((item, index) => {
item.style.backgroundColor = "white"
})
item.forEach((item, index) => {
item.style.cursor = "pointer"
item.addEventListener("click", () => {
console.log(index)
setColorByIndex(luckNum)
if(luckNum == index){
score++;
alert("You are lucky")
}else{
alert("You are unlucky")
}
document.getElementById("score").innerHTML = "Your score"+ score
})
})
}
function setColorByIndex(n) {
item = document.getElementsByClassName("item")
for (let i = 0; i < item.length; i++) {
if (i == n) {
item[i].style.backgroundColor = "red"
} else {
item[i].style.backgroundColor = "blue"
}
}
}
每次都可以通過直接分配來覆蓋事件
item.forEach((item, index) => {
item.style.cursor = "pointer"
item.onclick = () => {
console.log(index)
setColorByIndex(luckNum)
if(luckNum == index){
score++;
alert("You are lucky")
}else{
alert("You are unlucky")
}
document.getElementById("score").innerHTML = "Your score"+ score
};
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.