在這裏我有一個5秒後重定向用戶一個簡單的倒計時功能。的JavaScript:變量未定義內的if else
<script type="text/javascript">
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function() {
countdown();
}, 1000);
}
else
{
// Redirect the user
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof target === "undefined")
{
window.location.href = target;
}
}
};
var target = "/account/";
countdown(target);
</script>
的問題是,如果將5秒後,它的時間window.location.href
做重定向,「目標」變量是不確定的,我不知道爲什麼會這樣。
我已經研究和嘗試了各種解決方案,即使設置了「目標」的設置與「定時器」和「計數器」,但沒有奏效。我的目標是在每個功能實例上設置不同的「目標」。
UPDATE:設置countdown();
到countdown(target);
固定的「不確定」的問題,但window.location.href
對象仍然不重定向到target
變量值,可以做些什麼來解決這個問題?
程序中的「str」是什麼? – thefourtheye
對不起,它是「目標」,而不是更新後。 –
您沒有將任何參數傳遞給'setTimeout'回調中的'countdown'。 – user2357112