簡體   English   中英

單擊按鈕三次后如何激活新的function

[英]how to activated new function after button clicked for three times

我想在單擊按鈕 3 次后添加新的 function 並擦除/刪除以前的 function

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有 function 來清除 function toRed並在點擊 3 次后添加toBlue

刪除事件偵聽器並在單擊 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM