Calling function twice only

时间:2016-10-20 13:19:01

标签: jquery

I would like to create a button which can be used twice only, and which afterwards disables itself. As for now, I got this point but now i'm stuck..

<audio id="buzzer" src="https://xxx.mp3" type="audio/ogg"></audio>    
<input type="button" value="Start" id="start" /> 

<script type="text/javascript">    
    var buzzer = $('#buzzer')[0];  

    $('#start').on('click', function() {
        $('#buzzer').get(0).play();
    });

    $('input:button').click(function(){
        $('input:button').attr("disabled", true);
    });
</script>

Thanks for your help..

3 个答案:

答案 0 :(得分:2)

You have to create a counter.

See this example :

var maxclick=2;
var countclick=0;

$(".mybtn").click(function(){
  countclick++;
  majBtn();
  if(countclick>= maxclick)
  {
    $(this).prop("disabled",true);
  }
});

$(document).ready(function(){
  majBtn();
});

function majBtn()
{
  var countdown = maxclick-countclick;
  $(".mybtn").text("Click me "+countdown)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybtn">Click me</button>

答案 1 :(得分:0)

You just have to count how often the button has already been pressed and disable it after 2 clicks.

This snippet works fine for me:

var buzzer = $('#buzzer')[0], clicks = 0;

$('#start').on('click', function()
{
  $('#buzzer')[0].play();
  clicks++
  if(clicks == 2)
  {
    $(this).attr("disabled", "disabled");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="buzzer" src="https://xxx.mp3" type="audio/ogg"></audio>    
<input type="button" value="Start" id="start" />

答案 2 :(得分:0)

这可能对你有帮助..

var clicks =1;

var buzzer = $('#buzzer')[0];  

$('#start').click(function(){
if(clicks<2){      
     $('#buzzer').get(0).play();          
}
else{
     $('input:button').attr("disabled", true);
}
clicks++;
});