2012-03-25 85 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()