[英]How do I get setTimeout to read the value from the INPUT?
<input type="number" id="number">
<button onlcick="countdown()">COUNTDOWN</button>
var t = document.getElementById('number').value;
function countdown() {
setTimeout(function(){alert("hi!");}, t);
}
</script>
我希望setTimeout
獲得變量t
。 變量t
將獲得input
標簽中的任何4位數字,當您按下按鈕時,它將開始減去。 但是,當我嘗試按下按鈕時,它不會執行此操作。 代碼有問題嗎? 或者,這不是您的做法嗎?
您有2個錯誤,首先將onlcick
更改為onclick
,並將t
變量添加到函數countdown
因為您需要在單擊后獲取值,但在您的示例變量中將為空
function countdown() {
var t = document.getElementById('number').value;
setTimeout(function(){alert("hi!");}, t);
}
此外,您可以清除超時,以便在單擊后啟動新計時器,如此
var timer;
function countdown() {
var t = document.getElementById('number').value;
clearTimeout(timer);
timer = setTimeout(function(){alert("hi!");}, t);
}
主要問題:當調用函數時,需要讀取函數內部的輸入值:
function countdown() {
var t = document.getElementById('number').value;
setTimeout(function(){alert("hi!");}, t);
}
變量t
在頁面加載時初始化,並且在輸入值更改時不會自動更新。 您有責任從輸入中讀取新值。
另一件事(可能只是一個錯字)但是,屬性應該是onclick
。
看來你的按鈕上有一個拼寫錯誤它應該是<button onclick="countdown()">COUNTDOWN</button>
定義超時指針
window.hTimeOut = null;
function countdown() {
重置先前調用但未完成倒計時(超時)
if(window.hTimeOut!=null) clearTimeout(window.hTimeOut);
創建新的超時
window.hTimeOut = setTimeout(function(){
alert("hi!");
完成后重置超時指針
window.hTimeOut!=null;
並將新的時間價值傳遞給它
}, document.getElementById('number').value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.