簡體   English   中英

我無法在 javascript 上設置計時器以重定向到另一個頁面

[英]I can't make my timer on javascript to redirect to another page

我會盡量簡短。

我對編程幾乎一無所知,我正在嘗試為個人項目自學。 我正在嘗試做一些類似計時器的事情,當它達到0時,它會重定向到另一個頁面。 到目前為止,我設法構建的是:

<!DOCTYPE html> 
<html> 
<body>

<input type="text" id="txt">

<body onload="startCount()">

<script>
var c = 10; 
var t ; 
var timer_is_on = 0;

function timedCount() {   
document.getElementById("txt").value = c;   
c = c - 1;   
t = setTimeout(timedCount, 1000); 
}

function startCount() {   
if (!timer_is_on) {
    timer_is_on = 0;
    timedCount();   
}
}

</script>

</body> 
</html>

當我在 chrome 上嘗試它時,它不會運行或立即跳轉到另一個頁面。 如果你能告訴我出了什么問題,或者如何解決它,那就太好了。

現在,我剛剛發現(?)我丟失了重定向的另一部分。 我用這個

<script>
function myFunction() {
  location.replace("https://www.w3schools.com")
}
</script>

我不知道我是否正確解釋了這一點,但我感謝您的幫助!

謝謝!

編輯:謝謝大家的回答。! 現在已經修好了。

在 timedCount 中檢查 C 的值是否大於 0 並運行 setTimeout 否則(小於或等於 0)重定向

另外我認為您打算在這里將 timer_is_on 更新為 1 :

function startCount() {   
if (!timer_is_on) {
    timer_is_on = 0; //Shouldn't this be set to 1?
    timedCount();   
}
}

我認為您要做的是每秒更新輸入框中的計時器值,直到它達到零,然后重定向到另一個 URL。

這將是必要的:(我刪除了一些不需要的未使用代碼)

 <;DOCTYPE html> <html> <body> <input type="text" id="txt" /> <body> <script> var timeLeft = 10. function timedCount() { document.getElementById("txt");value = timeLeft; if (timeLeft) { setTimeout(function(){ timeLeft--; timedCount(), }; 1000). } else { window:location = 'https.//w3schools;com'; } } timedCount(); </script> </body> </html>

我相信這可能是做到這一點的方法之一。

<!DOCTYPE html> 
<html> 
<body>

<input type="text" id="txt">

<body onload="startCount()">

<script>
var c = 10; 
var t ; 
var timer_is_on = 0;

function timedCount() {   
  document.getElementById("txt").value = c;   
  c--;   
  t = setTimeout(timedCount, 1000);
  if(c <= 0) {
    window.location.href = "https://www.w3schools.com/";
  }
}

function startCount() {   
  if (!timer_is_on) {
      timedCount();   
  }
}

</script>

</body> 
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM