日期:2014-05-16  浏览次数:20358 次

给A标签添加事件出错
<!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=gb2312 "   />
<title> 无标题文档 </title>
</head>

<body>
<div>
<ul   id= "nav ">
<li>
<a   href= "# "> a1 </a>
</li>

<li>
<a   href= "# "> a2 </a>
</li>
</ul>
</div>


</body>
</html>
<script   type= "text/javascript ">

var   arr   =   document.getElementById( "nav ").getElementsByTagName( "a ");


for(i   =0   ;i   <arr.length;i++)
{
arr[i].onclick   =aa();
}


function   aa()
{
alert( " ");
}

</script>

----

为什么会报错?想不明白..

------解决方案--------------------
arr[i].onclick =aa(); ---> arr[i].onclick = aa;
------解决方案--------------------
arr[i].onclick =function () { alert( " "); }
------解决方案--------------------
那就用arr[i].onclick = function(i){alert(i);}
------解决方案--------------------
2个或2个以上参数可以通过数组赋值给value,如下:

<html>
<head>
<title> 无标题文档 </title>
</head>
<body>
<div>
<ul id= "nav ">
<li> <a href= "# "> a1 </a> </li>
<li> <a href= "# "> a2 </a> </li>
</ul>
</div>
</body>
</html>
<script type= "text/javascript ">
var arr = document.getElementById( "nav ").getElementsByTagName( "a ");
for(i =0 ;i <arr.length;i++)
{
arr[i].value=new Array(i,i);
arr[i].onclick =function() {for(var j=0;j <this.value.length;j++){alert(this.value[j]);}};
}
</script>
------解决方案--------------------
for(var i =0,j=0;i <arr.length;i++)
{
arr[i].onclick = function(){aa(j++)};
}