2012-10-24 49 views
-2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 



<script language="javascript" type="text/javascript"> 

(function setFont() { 
var i; 
for (i = 0; i < document.all.length; i++) { 
document.all[i].style.fontFamily = "Verdana"; 
document.all[i].style.fontSize = "16"; 
document.all[i].style.color="black"; 
} 
})(); 

(function abc(a) 
{ 
alert(a); 
ansArray = ['a']; 
for(i=1;i<=a;i++) 
{ 
document.write('<input type = "button" value = "a">'); 
document.write('<input type = "button" value = "b">'); 
} 
var myButton = document.getElementsByTagName("input"); 
//alert(myButton.length); 
myButton[0].onclick = function() { 
    if(ansArray[0] == 'a') 
     myButton[0].style.backgroundColor = "green"; 
    else 
     myButton[0].style.backgroundColor = "red"; 
}; 

myButton[1].onclick = function() { 
    if(ansArray[0] == 'b') 
     myButton[1].style.backgroundColor = "green"; 
    else 
     myButton[1].style.backgroundColor = "red"; 
}; 
})(); 
setFont(); 
</script> 
</head> 

<body onload="abc(2)"> 
</body> 
</html> 

JavaScript函數abc(a)沒有獲得從<body onload = "abc(5)">傳遞的值2。它說未定義。如何在JavaScript函數中傳遞參數。我早些時候發佈了它,但參數並不存在,給出了我發現問題的參數。請幫助我。在此先感謝Javascript函數未通過paramrter

+0

調用一個函數裏面的回合制腳本導致當腳本標記完全加載時,而不是onload事件時,你應該真的刪除那些括號... –

回答

1

您的函數是一個閉包,它不暴露給公衆,但它創建後立即執行。 然後它消失了。

這不是看起來很酷,它有它的目的。只是要正常功能得到它的工作


(function(a) { 
    // immediately called and 'garbaged' 
})(a); 

function publicAlwaysCallable(a) { 
    console.log(a); // call me when you like 
} 
+0

正常的功能我試過在IE中無法正常工作,但工作正常in chrome and firefox – user1767304

+0

@ user1767304使用['window.onload'](http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html)和'

1

您不必在這種情況下使用即時功能。聲明這樣的:

function abc(a) { ... } 

如果由於某種原因,你要封裝你的代碼封閉,你可以做這樣的:

(function(export) { 
    export.abc = function(a) { ... }; 
    ... 
})(window); 
+0

函數abc(a){...} - 這種方式不起作用在IE瀏覽器,但在鉻和火狐工作正常 – user1767304

+0

我得到了在onload事件中回答在腳本體上被調用的函數。感謝每一個機構 – user1767304

+0

@ user1767304你應該接受最有用的答案。 –

0

正常功能(未封閉)功能ABC(一)使用按鈕點擊處理程序的{...}將在腳本結尾被調用。不在頁面的onload事件上。現在它在IE9中也有效

感謝大家的寶貴建議。