我想在單擊按鈕 3 次后添加新功能并擦除/洗掉以前的功能
.html 檔案:
<body>
<div id="background">
<p>this background white, before</p>
</div>
<button class="btn-1">change color</button>
</body>
javascript:
const btn1 = document.querySelector(".btn-1") ;
const bg = document.getElementById("background")
const toRed = ()=>{
bg.style.backgroundColor = "red";
}
const toBlue = ()=>{
bg.style.backgroundColor = "steelblue";
}
btn1.addEventListener('click', toRed);
// 我希望這個btn1具有清除功能toRed并在單擊 3 次后添加toBlue的功能
uj5u.com熱心網友回復:
洗掉事件偵聽器并在單擊 3 次時添加一個新偵聽器:
const btn1 = document.querySelector(".btn-1");
const bg = document.getElementById("background");
var redClicked = 0;
const toRed = ()=>{
bg.style.backgroundColor = "red";
redClicked ;
if (redClicked >= 3) {
btn1.removeEventListener('click', toRed);
btn1.addEventListener('click', toBlue);
}
}
const toBlue = ()=>{
bg.style.backgroundColor = "steelblue";
}
btn1.addEventListener('click', toRed);
<body>
<div id="background">
<p>this background white, before</p>
</div>
<button class="btn-1">change color</button>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416958.html
標籤:
下一篇:將回傳的物件推送到物件陣列中
