简体   繁体   English

单击按钮三次后如何激活新的function

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

i want to add new function after i clicked the button 3 times and erase/remove the former function我想在单击按钮 3 次后添加新的 function 并擦除/删除以前的 function

html file: html 文件:

<body> 
  <div id="background">
    <p>this background white, before</p>
  </div>
  <button class="btn-1">change color</button>
</body>

javascript: 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);

// i want this btn1 have function to clear function toRed and add toBlue instead after clicked 3 times // 我希望这个btn1有 function 来清除 function toRed并在点击 3 次后添加toBlue

remove the event listener and add a new one when it was clicked three times:删除事件侦听器并在单击 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