我要做的是用户将一个数字输入到文本框中,然后浏览器将弹出一个警告,提示它将倒计时...秒。以下是我的代码,但似乎无济于事。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function timer(){
if(document.getElementById("time").value=="")||(isNaN(document.getElementById("time").value)==true)
alert("Please input a number");
else
alert("Start counting down ",(parseInt(document.getElementById("time").value))/1000," seconds");
setTimeout("alert('Times out');",time);
}
</script>
<input type="text" id="time"/>
<button onClick="timer();">Submit</button>
</body>
</html>
答案 0 :(得分:0)
您缺少time
变量。是undefined
。
另外,不要在setTimeout
内评估函数:
var EL_time = document.getElementById("time");
var EL_startTime = document.getElementById("startTime");
function end () {
alert("Time out!");
}
function start() {
var time = parseInt(EL_time.value); // the missing `time`
// Early return
if (!Number.isInteger(time)) return alert("Please input a number");
// Everything OK
alert(`Start counting down ${time / 1000} seconds`);
setTimeout(end, time);
}
EL_startTime.addEventListener("click", start);
Milliseconds: <input id="time" type="text">
<button id="startTime">Start</button>