我有一个倒计时脚本,可以重定向到文件。它有一个循环,并且变量只运行一次就没有定义。

如何保持url变量的值?

        <a id="" onClick="doTimer('http://www.domain.com/downloadfile.php?photo=foo.jpg')" href="#"><button id="download">Download this photo</button></a>

        var timer_is_on=0;
        var countdownfrom=5
        var currentsecond=document.getElementById('countdown').innerHTML=countdownfrom+1

        function countredirect(url)
        {
            if (currentsecond!=1)
            {
                currentsecond-=1
                document.getElementById('countdown').innerHTML = currentsecond;
            }
            else
            {
                window.location=url
                return
            }
            setTimeout("countredirect()",1000)
        }
        function doTimer(url)
        {
            if(!timer_is_on)
            {
                document.getElementById('download').innerHTML="Your download starts in <span id=\"countdown\"></span>seconds";
                timer_is_on=1;
                countredirect(url)
            }
        }

最佳答案

setTimeout("countredirect()",1000)


您没有将任何参数传递给countredirect函数。

将字符串传递给setTimeoutsetInterval通常不是一个好主意(给您各种范围问题)。传递一个函数代替:

setTimeout(function() {
    countredirect(url);
}, 1000);


在较新的浏览器(或带有填充程序)中,您也可以使用.bind() bind返回一个新函数):

setTimeout(countredirect.bind(null, url), 1000);

09-25 17:30
查看更多