Javascript undefined var window.location

时间:2016-04-02 17:16:02

标签: javascript

我试图创建一个动态功能,使重定向,但它不起作用 它返回给我' undefined'

这是HTML代码:

['to study', 'to talk', 'to make']
['to make', 'to run', 'to practice']
['to run', 'to talk', 'to take']
['to arrive', 'to practice', 'to suck']
['to run', 'to search', 'to practice']
['to arrive', 'to suck', 'to talk']
['to search', 'to like', 'to take']
['to take', 'to play', 'to study']
['to study', 'to take', 'to practice']
['to suck', 'to search', 'to run']
['to play', 'to suck', 'to make']
['to suck', 'to talk', 'to search']

这是JavaScript代码:

<p>You will be redirected to the page X in <span id="time">4</span> seconds..</p>

我也尝试过:

 var seconds;
 var temp;

 function countdown(page) {    
     seconds = document.getElementById('time').innerHTML;
     seconds = parseInt(seconds, 10);
     if (seconds == 1) {
         temp = document.getElementById('time');
         temp.innerHTML = '0. If you are not, please click <a href="' + page + '">here</a>.';
         window.location = page;
         return;
     }
     seconds--;
     temp = document.getElementById('time');
     temp.innerHTML = seconds;
     timeoutMyOswego = setTimeout(countdown, 1000);
 }
 countdown('/asimplepage/asdfgh.html');

1 个答案:

答案 0 :(得分:2)

问题在于这一行:

 timeoutMyOswego = setTimeout(countdown, 1000);

setTimeout调用countdown时,它不会传递最初将该功能关闭的page参数。因此,countdown运行的第二个(以及后续时间),page没有传递任何内容。

将行更改为:

 timeoutMyOswego = setTimeout(function(){countdown(page)}, 1000);

这指示setTimeout()函数安排对匿名函数的调用,该函数将调用countdown并在{1}}之后提供countdown变量值page第二