我想做一個倒計時網站,一切工作正常,但它不需要在文本框中的數字,我已經啓用,只能輸入數字。每次我輸入一些數字時,都會顯示NaN:NaN。Javascript Number輸入倒數
的Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<link href='https://fonts.googleapis.com/css?family=Merriweather:700italic' rel='stylesheet' type='text/css'>
<title>Pizza Timer</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/styles.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../0../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="js/bootstrap.min.js"></script>
<script src="js/app.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="test" background="pizza.jpg">
<h1 class="text-center"><strong>Pizza Timer!</strong></h1>
<p class="text-center"><small>The Best Pizza Timer In The World!</small></p>
<p id="demo"></p>
<div class="timer">
<span id="time">The Timer Will Start When You Click The Button!</span>
</div>
<div class="row">
<div class="container">
<input id="input1" class="form-control" type="number" placeholder="Minutes" />
<input id="input2" class="form-control" type="number" placeholder="Seconds" />
<button id="timerstarter" class="btn btn-success" onclick=buttonTimer()>Start!</button>
</div>
</div>
</body>
</html>
app.js
var number1 = document.getElementById('input1').value;
var number2 = document.getElementById('input2').value;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var countdown = setInterval(function() {
minutes = parseInt(timer/60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
alert("Your Pizza Is Ready!");
clearInterval(countdown);
}
}, 1000);
}
function buttonTimer (number1, number2) {
var Minutes = number1*60+input2,
display = document.querySelector('#time');
startTimer(Minutes, display);
};
需要ParseInt給number1和number2 – Nirus
'var Minutes = number1 * 60 + input2'什麼是'input2'?它不應該是'數字2'嗎?你應該真的檢查你的控制檯是否有錯誤。在Firefox或Chrome中按「F12」,然後單擊控制檯選項卡。有機會,你會看到一些'未定義的'錯誤。 –
'parseInt'接受一個字符串。你甚至在數字之前就已經在做數學了。 –