如何在js中启用和禁用时间?

时间:2018-04-09 03:55:02

标签: javascript html

我想启用单击启用按钮的时间并禁用单击禁用按钮的时间... 的 HTML

 <p id="demo"></p> 
 <select>
    <option onselect="enable()">Enable</option>
    <option onselect="disable()"> disable</option>
 </select>

的JavaScript

 var myVar = setInterval(myTimer, 1000);

function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}


function enable() {
     document.getElementById("demo").innerHTML = "block";

}

function disable() {
    document.getElementById("demo").innerHTML = "none";
}

4 个答案:

答案 0 :(得分:2)

你的disable函数中的

清除了inetrval

function disable() {
   clearInterval(myVar);
   document.getElementById("demo").style.display = "none"; // set style not HTML
}

要再次启用时间,请将enable方法修改为:

function enable() {
   document.getElementById("demo").style.display = "block";
   myVar = setInterval(myTimer, 1000);
}

答案 1 :(得分:2)

您需要设置样式来更改元素的样式,而不是innerHTML

const demo = document.getElementById("demo");
setInterval(myTimer, 1000);
function myTimer() {
  var d = new Date();
  demo.textContent = d.toLocaleTimeString();
}
const select = document.querySelector('select');
select.addEventListener('change', () => {
  demo.style.display = "block";
  else demo.style.display = "none";
});
<p id="demo"></p>
<select>
    <option value="Enable">Enable</option>
    <option value="Disable">Disable</option>
 </select>

此外,在插入文字(不是HTML标记)时,请务必使用textContent而非innerHTML - 它更快更安全。

答案 2 :(得分:1)

我建议您使用onchange的{​​{1}}事件(因为据我所知,没有select事件)并检查所选的值。然后,如果是onselect,请使用Disable清除时间间隔,否则重新开始:

&#13;
&#13;
clearInterval
&#13;
var myVar = setInterval(myTimer, 1000);

function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

function toggle(select) {
  let demo = document.getElementById("demo");
  if (select.value === 'Disable') {
     clearInterval(myVar);
     demo.style.display = 'none';
  } else {
    demo.style.display = 'block';
    myVar = setInterval(myTimer, 1000);
  }
}
&#13;
&#13;
&#13;

答案 3 :(得分:1)

你去了,以下是更正

var myVar = setInterval(myTimer, 1000);

function myTimer() {
  var d = new Date();
  document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

function enable() {
  document.getElementById("demo").style.display = "block"; //changed `innerHTML` with `style.display`
}

function disable() {
  document.getElementById("demo").style.display = "none"; //changed `innerHTML` with `style.display`
}
<p id="demo"></p>
<select onchange='window[this.value]()'> <!-- added onchange -->
    <option value='enable'>Enable</option> <!--  added `value` removed `onselect` -->
    <option value='disable'>Disable</option> <!-- same as above -->
 </select>

在上面的代码中,此行window[this.value]()将根据所选的选项调用enabledisable等函数。