Javascript函数前的未定义变量

时间:2012-07-03 22:00:13

标签: javascript variables

我有一大堆javascript来自http://www.developphp.com/view.php?tid=1248,我看到了“未定义变量 - 广播”的错误。

function cdtd(broadcast) {
    /* expected date format is Month DD, YYYY HH:MM:SS */
    var nextbroadcast = new Date(broadcast);
    var now = new Date();
    var timeDiff = nextbroadcast.getTime() - now.getTime();
    if (timeDiff <= 0) {
        clearTimeout(timer);
        document.getElementById("countdown").innerHTML = "<a href=\"flconlineservices.php\">Internet broadcast in progress<\/a>";
        /* Run any code needed for countdown completion here */
    }
    var seconds = Math.floor(timeDiff / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);
    hours %= 24;
    minutes %= 60;
    seconds %= 60;
    document.getElementById("daysBox").innerHTML = days + " d";
    document.getElementById("hoursBox").innerHTML = hours + " h";
    document.getElementById("minsBox").innerHTML = minutes + " m";
    // seconds isn't in our html code (javascript error if this isn't commented out)
    /*document.getElementById("secsBox").innerHTML = seconds + " s";*/
    var timer = setTimeout('cdtd(broadcast)',1000);
}

“广播”从具有此<script type="text/javascript">cdtd("<?php echo $nextbroadcast; ?>");</script>的页面传递。 $ nextbroadcast基于用户查看页面的日期/时间。

我尝试了var broadcast;var broadcast = "";var broadcast = null;。每当我尝试在函数之前声明变量时,它就会破坏脚本。

我做错了什么吗?脚本工作正常,但我宁愿没有错误。

2 个答案:

答案 0 :(得分:2)

这可能是问题所在:

var timer = setTimeout('cdtd(broadcast)',1000);

您应该在var timer;函数之上声明cdtd(),然后将其设置为函数下面的 之外的

var func = 'cdtd(' + broadcast + ')';

timer = setTimeout(func,1000);

答案 1 :(得分:2)

更改以下行:

var timer = setTimeout('cdtd(broadcast)',1000);

对此:

var timer = setTimeout(function() { cdtd(broadcast); }, 1000);