need to diminish number by 1 every time message pops up

时间:2017-12-18 06:28:26

标签: javascript jquery

I am a little stuck here and don't know how to proceed. need to diminish number by 1 every time message pops up.

var counter = 1;
$(document).ready(function() {
  if (counter == 1) {
    counter++;
    $('#cntVal').html(function(i, val) {
      return +val - 2
    });
  } else {
    $('#cntVal').html(function(i, val) {
      return +val - 1
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="cnt">You still have (<span id="cntVal">3</span>) more tries left. Good luck!</p>
should have 3 tries only so first message You still have 2 more tries left. then You still have 1 more tries left.

but in this code always show 2 more tries :(

1 个答案:

答案 0 :(得分:4)

According to your code, each time $(document).ready(function(){}); called, for diminish number by one you need to do event trigger.

var counter = 1;
$(document).ready(function() {

  $('#cnt').on('click', function() {
    if (counter == 1) {
      counter++;
      $('#cntVal').html(function(i, val) {
        return +val - 1
      });
    } else {
      $('#cntVal').html(function(i, val) {
        return +val - 1
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="cnt">You still have (<span id="cntVal">3</span>) more tries left. Good luck!</p>

I have applied event trigger on click at paragraph.