先來一段代碼,大家猜猜在各種瀏覽器下的結果會是怎么樣的呢?function f(){ var s = 'arguments.length:'+arguments.length+'; ';for(var i=0,n=arguments.length;i< n;i++){ s += ' ['+i+']:'+arguments[i]+'; '; } alert(s); } setTimeout(f,500,"javascript","AAA"); setTimeout與setInterval的參數和用法是一樣的,只是功能不同
各種瀏覽器下的結果: IE(6,7,8)是: arguments.length:0; Opera(6,7,8)是: arguments.length:2; [0]:javascript; [1]:AAA; Firefox(3.0)是: arguments.length:3; [0]:javascript; [1]:AAA; [2]:0;
原因分析: 1) IE系統瀏覽器: 首先,我們看看微軟出的DHTML參考手冊中是如何說的: setTimeout Method Evaluates an expression after a specified number of milliseconds has elapsed. Syntax iTimerID = window.setTimeout(vCode, iMilliSeconds [, sLanguage])
Parameters vCode Required. Variant that specifies the function pointer or string that indicates the code to be executed when the specified interval has elapsed. iMilliSeconds Required. Integer that specifies the number of milliseconds. sLanguage Optional. String that specifies one of the following values: JScript Language is JScript. VBScript Language is VBScript. JavaScript Language is JavaScript. 在IE中,setTimeout接收3個參數,第3個參數表示腳本語言的類型,如果你再傳入更多的參數,是無意義的。因此,在IE中,以下兩種都是對的。 setTimeout('alert(1)', 50); setTimeout('msgbox "終止、重試、忽略,您看著辦吧。", vbAbortRetryIgnore + vbDefaultButton2, "告訴您"', 50, 'VBScript');
2) Mozilla系統瀏覽器: Mozilla官方網站上 Gecko DOM Reference 手冊中是如何說的: window.setTimeout Summary Executes a code snippet or a function after specified delay. Syntax var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]); var timeoutID = window.setTimeout(code, delay); 前兩個參數都一樣,沒差別,從第三個參數就不同了。因為目前只有IE瀏覽器支持多種語言的腳本,其它瀏覽器只支持js腳本所以不需要傳語言類型的參數。 Mozilla把傳給setTimeout的第3個以及更后面的更多參數依次的傳給前面的func做為參數。 Firefox, Opera, Safari, Chrome等等也都是如此。 Mozilla中存在一個BUG,就是一開始的例子中,本來只傳遞了兩個參數,結果卻出來了三個參數,就是說存在一個沒有意思的參數
4. 各瀏覽器中的解決方法
IE是不支持在setTimeout中給被調用的函數傳參數的,為了瀏覽器世界的和諧,我們可以把函數調用參數包裹進新的匿名函數中。示例:
var width = $("#ctl00_cphContent_divGallery td").css("width"); //畫廊中每個縮略圖的寬度 width = parseInt(width, 10); //將寬度保存為整數 var gallery = document.getElementById("ctl00_cphContent_divGallery"); //獲取畫廊的容器元素 MyMar = setInterval(function(){Marquee(width, gallery, "left")}, 20); //設置滾動動畫,每20毫秒調用一次 通過在匿名函數中調用帶參數的自定義函數,這樣的語句在IE和非IE中都可以運行。