-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) 没有获得从 传递的值 2 <body onload = "abc(5)">。它说未定义。如何在javascript函数中传递参数。我之前也发布了它,但是参数不存在,在给出参数时我发现了问题。请帮助我。提前致谢

4

3 回答 3

1

您的函数是一个闭包,它不向公众公开,但它在创建后立即执行。然后它就消失了。

它不是看起来很酷,它有它的目的。只需制作正常功能即可使其正常工作


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

对比

function publicAlwaysCallable(a) {
  console.log(a); // call me when you like
}
于 2012-10-24T07:50:32.390 回答
1

在这种情况下,您不必使用即时功能。像这样声明它:

function abc(a) { ... }

如果由于某种原因你想将你的代码封装成闭包,你可以这样做:

(function(export) {
    export.abc = function(a) { ... };
    ...
})(window);
于 2012-10-24T07:53:13.753 回答
0

The normal function (not closure) function abc(a){ ... } with the button click handlers are to be called at the end of the script. Not on onload event of the page. Now it works in IE9 also

Thanks everybody for your valuable suggestions.

于 2012-10-26T07:42:53.687 回答