2012-03-25 48 views
0

该函数接受参数whichImage。这是我们正在使用的图像的对象HTMLImageElement。图像宽度将减半,然后3秒后,它将恢复到正常宽度。但是,应该在3秒后执行的setTimeout代码会失败,并显示错误消息,指出没有定义whichImage。为了使这个功能正常工作,我需要纠正什么?函数内的setTimeout失败

function resizeImageFunction(whichImage){ 
    // Get the width of the image 
    alert(whichImage); 
    var width = whichImage.width; 
    var halfwidth = Math.round(width/2); 
    whichImage.width=halfwidth; 
    setTimeout("whichImage.width=width;",3000); 
} 
+0

你可能想接受一些答案来奖励他们吗? – einstein 2012-03-25 17:09:14

回答

1
function resizeImageFunction(whichImage){ 
    // Get the width of the image 
    alert(whichImage); 
    var width = whichImage.width; 
    var halfwidth = Math.round(width/2); 
    whichImage.width=halfwidth; 

    setTimeout(function(){ 
     whichImage.width=width; 
    },3000); 
} 
+0

很好,谢谢 – user1019490 2012-03-25 06:11:36

0

你需要用你的代码块像一个匿名函数:

setTimeout(function() { 
    whichImage.width=width; 
}, 3000); 
0

尝试:


setTimeout(function() { 
    whichImage.width=width; 
},3000); 
0

你不需要使用eval这个

setTimeout(function() { whichImage.width=width; } ,3000); 

这里是你的功能

function resizeImageFunction(whichImage){ 
    var halfwidth = Math.round(width/2); 
    whichImage.width=halfwidth; 
    setTimeout(function() { whichImage.width=width; } ,3000); 
} 
1

有关问题的解释如下:

当你传递一个字符串setTimeout(),该字符串将被eval()在全球范围内评估。因此,您所调用的任何函数或您在其中引用的变量都必须在全局范围内可用。这就解释了为什么你不能为你的函数引用一个局部变量或参数,因为它们都不在全局范围内,因此当eval()试图找到它们时,它会在全局范围内查找,但它们不在那里。

当您使用内联匿名函数改变setTimeout()功能如下:

setTimeout(function() { 
    whichImage.width = width; 
}, 3000); 

现在你有真正的javascript代码(不是一个字符串),在适当位置评估它没有使用eval()存在,由于关闭,您可以完全访问局部变量和封闭函数的参数,从而使您可以访问whichImage(参数)和width(局部变量),因此您的代码可以工作。

这是理由#14,你应该总是使用真正的JavaScript函数引用或匿名函数声明,而不是将字符串传递给setTimeout()