JQuery:如何在计时器达到零时显示丢失屏幕

时间:2016-05-11 04:14:59

标签: jquery

HTML:

<div id="countdown">20</div>

JS:

var doUpdate = function() {
$('#countdown').each(function() {
    var count = parseInt($(this).html());
    if (count !== 0) {
        $(this).html(count - 1);
    }
 });
};

function firstLevel() {

    var interval = setInterval(doUpdate, 1000);

    $("select").change(function() {

    if ( certain selection is selected ) {

        counter++; // add one to the counter

        // if all selections are properly selected
        if (counter === 8 && $countdown.text() > 0) {
            // win condition
        } 

    }

   }); 

    if (counter !== 8 && $countdown.text() === 0) {
       // LOSS CONDITION. PROBLEM HERE
    } 
}

所以我有8个div,每个都有一个选择形式,如果他们在一定的秒数内为每个选择选择正确的选项,则玩家“获胜”,如果他们未能在每个选项中选择所有正确的选项,他们会“失败”选择。但是计时器不起作用。我认为这是因为在我的丢失情况下,$ countdown.text()只设置一次,并且不会随着计时器更新而更新。我该如何解决?我想出的解决方案是:

setTimeout(
    function() {
        $firstlevel.hide(); 
        $gameover.show();
    }, 20000);

哪个有效但似乎是一个可怕的解决方案。

编辑:Nvm它不起作用。即使您赢了,它也会在20秒后显示丢失屏幕。

1 个答案:

答案 0 :(得分:2)

我会使用clearInterval();data attributes.off()来执行此操作,如下所示:

在示例中,快速选择1,2,3赢得

&#13;
&#13;
var $selects = $("select");
var $countdown = $('.countdown');
// start a timer to update the countdown
// but keep a reference to it so we can call clearInterval(interval); later
var interval = setInterval(function() { 
  var count = parseInt($countdown.html());
  if (count !== 0) $countdown.html(count - 1);
  else {
    // countdown ended so the user lost, remove event handlers and stop timer
    $selects.off(); // remove change function
    clearInterval(interval);
    alert('you lost');
  }
}, 1000);

$selects.change(function() {
  // when a select changes, loop over them all
  var won = true;
  $selects.each(function() {
    var $this = $(this);
    var val = $this.val().toString();
    var correct = $this.data('correct').toString();
    // compare selected val to correct val stored as data attribute 
    if (val != correct) {
      won = false;
      return false;
    }
  });
  if (won) { // if all right, user wins, remove event handlers and stop timer
    $selects.off();
    clearInterval(interval);
    alert('you won');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
  5</div>
<select name="" class="" data-correct="1">
  <option value="select an option">select an option</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<select name="" class="" data-correct="2">
  <option value="select an option">select an option</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<select name="" class="" data-correct="3">
  <option value="select an option">select an option</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
&#13;
&#13;
&#13;