简体   繁体   中英

How do I make a button disappear after a certain amount of clicks

I have a button is it possible to make it disappear if I click it say 5 times? need to know for a little project I'm working on! any response is appreciated!

Use this Code

HTML:

<button type='button' id='button_test_clicks'>
  Click me!
</button>

JavaScript:

(function(){
  var counter=0; // counter clicks initialization
  var button=document.getElementById('button_test_clicks'); //Our button
  button.addEventListener("click",function(){ //add a click event to button
    counter++; //incement the counter
    console.log(a);
    if(counter==5){
      button.style.display = 'none'; //hide if the clicks reached to 5
    }
  });
})();

But whenever the page refresh happens counter sets to zero, to avoid refresh problems learn about localStorage in javascript.

Assign id to your button.
<Button id='myButton' onclick="myFunction()">

On every click of button, keep incrementing the counter (I think you know how to do it)

After the counter is reached, document.getElementById("Your_button_id_here").style.visibility = "hidden";

<script>
var counter=0;
function myFunction() {
    //increment counter
    counter+=1;
    if(counter>4)
        document.getElementById("Your_button_id_here").style.visibility = "hidden"
}
</script>

However, I think disabling would be more proper: document.getElementById("Your_button_id_here").disabled=true

You could have a simple script like this :

    var nbClicks=0;
    function btnOnClick(btn){
      if(++nbClicks>5){btn.style.display='none';}
    }

And use it like that : <input type="button" onclick="btnOnClick(this)" value="Click me 6 times !">

每次单击时,只需增加变量的值,并在获得所需的数字后,用css和js将其隐藏即可。

I made a small example with jQuery

 var count = 0; $("#b1").click(function() { count++; if (count >= 5) { $("#b1").hide(); } }); 
 <html> <header> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </header> <body> <button id="b1">5 Clicks</button> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM