【发布时间】:2011-11-11 16:38:14
【问题描述】:
我真的在为这个问题苦苦挣扎——当然我错过了一些简单的东西。
这是代码:-
function webcamupdate(webcamurl) {
alert("I am a function to update the webcam with the url "+webcamurl);
}
function countdown(callback) {
alert(callback);
setTimeout("callback()", 10000);
}
var theurl = "THIS IS THE URL";
countdown(function(){ webcamupdate(theurl); });
如您所见,我正在尝试构建一个倒计时功能(有更多代码,但我刚刚发布了基础知识),它将在 10 秒后运行一个功能(在本例中是更新网络摄像头)。
如果函数没有参数,一切正常,但是 coundown 函数中的警报(回调)返回以下内容:-
function(){ 网络摄像头更新(theurl); }
当 webcamupdate 函数由于“webcamurl”未定义而运行时,这当然会导致脚本崩溃。
alert(callback) 实际上需要说的是:-
function(){ webcamupdate("这是网址"); }
即它在将参数“theurl”与函数一起传递之前对其进行评估。
任何想法将不胜感激
编辑
我想我可能误导了你我使用警报而不是函数(我只是想保持简单!)
这是原始代码(仍然被删减,但给你一个更好的主意)。
function webcamupdate(url) {
document.getElementById("cruisecam").src=url+"&rand="+Math.random();
countdown(30,"Webcam",function(){ webcamupdate(url); });
}
function countdown(currentcount,displayelement,callback) {
var displaytext;
if (currentcount == 0 ) displaytext = displayelement+" is refreshing now";
else displaytext = displayelement+" updating in "+currentcount+" seconds";
if (trackingcountdown.hasChildNodes()) clearelement("trackingcountdown");
trackingcountdown.appendChild(document.createTextNode(displaytext));
if (currentcount == 0) {
countdown(currentcount,displayelement,callback)
}
else {
currentcount--;
var countdownparameters=currentcount+',"'+displayelement+'",'+callback;
setTimeout("countdown("+countdownparameters+")", 1000);
}
}
//The function is called on window loading with
//countdown(30,"Webcam",function(){ webcamupdate(url); });
//clearelement is another function (not listed) that clears the node.
基本上,重要的是倒计时函数 - 它需要 3 个参数 - 以秒为单位的倒计时时间、显示倒计时的 DOM 元素以及超时运行的函数。
如果第三个参数(函数)没有任何自己的参数 - 例如webcam() - 它工作正常,但是当我们尝试添加 webcam("webcampic.jpg") 时它不起作用,因为函数试图运行 webcam(url) 而不是 webcam("webcampic.jpg")。
显然,最简单的解决方案就是将 url 设为全局变量,但这不是好的做法,并且会阻止我通过 js 文件在其他页面上使用倒计时代码。 帮忙!
【问题讨论】:
-
“什么警报(回调)实际上需要说...”这不是 JavaScript 的工作原理。
-
那么当一切都说完了,警报应该说什么呢?
标签: javascript function arguments