javascript 没有读取 html 中的值

javascript dosen't read the value in html

所以我想制作一个程序,从您选择的值开始倒计时,但问题是当我尝试将值设为 javascript 它不起作用,但是当我输入值时html 有效

这是我的 html 代码

<body>
<div id="count">
    <input id="time" type="number" min="0">
    <button id="button">Press here to begin the countdown</button>
</div>
<script src="lol.js"></script>

这是我的 javascript 代码

var count = document.getElementById("count"),
    seconds = document.getElementById("time").value ,
    btn = document.getElementById("button"),
    secondPass;
    countDown = setInterval(function() {
        secondPass()
    } , 1000);
btn.onclick =         
function secondPass(){
    var minutes = Math.floor(seconds / 60),
        remseconds = seconds % 60;
    count.innerHTML = minutes + ":" + remseconds;
    if (remseconds < 10){
        remseconds = "0" + remseconds;
    }
    if (seconds> 0 ){
        seconds = seconds - 1;
    }   
    else {
        clearInterval(countDown)
        count.innerHTML = "done !"
    }
}

主要错误 - 声明 seconds 变量时的时间 - 时间输入为空。 我修复了你的例子,所以你可以找出问题所在

var count = document.getElementById("count"),
    seconds,
    btn = document.getElementById("button"),
    countDown
  
  btn.onclick = function() {
    seconds =  document.getElementById("time").value;
    countDown = setInterval(function() {
      secondPass()
    }, 1000);
  }
    
function secondPass(){
     console.log('S', seconds)
    var minutes = Math.floor(seconds / 60),
        remseconds = seconds % 60;
    count.innerHTML = minutes + ":" + remseconds;
    if (remseconds < 10){
        remseconds = "0" + remseconds;
    }
    if (seconds> 0 ){
        seconds = seconds - 1;
    }   
    else {
        clearInterval(countDown)
        count.innerHTML = "done !"
    }
}

您的代码中的问题是您试图在 value 输入之前获取它。 如果我没理解错的话,你想要这个:

var count = document.getElementById("count"),
    btn = document.getElementById("button"),
    secondPass;


btn.addEventListener("click", secondPass);

function secondPass() {
    var seconds = document.getElementById("time").value

    var countDown = setInterval(function () {
        var minutes = Math.floor(seconds / 60),
            remseconds = seconds % 60;
        count.innerHTML = minutes + ":" + remseconds;
        if (remseconds < 10) {
            remseconds = "0" + remseconds;
        }
        if (seconds > 0) {
            seconds = seconds - 1;
        }
        else {
            clearInterval(countDown)
            count.innerHTML = "done !"
        }
    }, 1000);
}
<div id="count">
    <input id="time" type="number" min="0">
    <button id="button">Press here to begin the countdown</button>
</div>