更改var onclick按钮,javascript

时间:2015-04-10 18:50:43

标签: javascript jquery

这个计时器我需要一个暂停按钮。不幸的是,它没有用。

当点击id“button-pause”时,我需要设置“var pressed = true”。

如果没有,请运行下面的脚本“if(!pressed){”并让“var pressed = false”。

怎么了?

HTML

<span id="button-pause">
  <span class="music"></span>
  <img src='img/icons/pause.png' alt='Stop music'>
</span>

的JavaScript

var minutes = 60;

// Set number of seconds remaining after which to trigger a warning color
var warning = 59;
var pressed = false;
k = document.getElementById('button-pause');

k.onclick = function () {
  pressed = true;
}

if(!pressed){
  // Declare variables
  var timerEl, seconds, timer;

  // Get a reference to the HTML element
  timerEl = document.getElementById('tim');

  // Calculate total seconds
  seconds = 1*minutes;

  // Updates the timer element
  function updateTimer() {
    var m,s;

    // Get whole minutes
    m = Math.floor(seconds/60);

    // Get left-over seconds
    s = seconds % 60;

    // Pad anything below 10 with a leading zero
    s = (s < 10) ? "0"+s : s;

    // Write time to HTML element
    timerEl.innerHTML = m + ":" + s;

    // Decrement seconds
    seconds--;

    // Add warning class when we hit threshold
    if(seconds < warning) {
      timerEl.classList.add('warning');
    }
    // Clear timer when we hit zero
    if(seconds < 0) {
      clearInterval(timer);
      window.location.href='index.php?mode=workout&workoutid=test&status=done';
    }
  }
}

timer = setInterval(updateTimer, 1000);

1 个答案:

答案 0 :(得分:0)

你的第一个问题是使用相同的变量做两件事

var pressed = false;  <-- store a boolean
pressed = document.getElementById('button-pause');  <--override the boolean  with the button

第二个问题是单击按钮时JavaScript代码不会改变。它将设置变量,但已运行的代码不会神奇地更新。您需要将代码添加到某种功能中,并在单击按钮或加载页面时触发它。