<!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>无标题文档</title>
<style type="text/css">
li{border:1px solid #f30;list-style:none;margin:3px; cursor:pointer}
</style>
</head><body>
<ul id="show">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</body>
<script language="javascript">
function show(){
var a=document.getElementById("show").getElementsByTagName("li");
for(var i=0;i<a.length;i++){
a[i].onclick=function(){
alert(i)
}
}
}
show()
</script>
</html>点击"li"的时候我原本打算是让它分别弹出i的值(1,2,3,4),可是它老是弹出4,也就是a.length的值,这是为什么啊?
改成下面的就对了
a[i].onclick = new Function("alert(" + i + ")");
var a=document.getElementById("show").getElementsByTagName("li");
alert(a)
for(var i=0;i<a.length;i++){
a[i].onclick=function(){
alert(this.innerHTML)
}
}
}
show()
它都是全局变量i,
在循环执行完以后他的值是4,所以老是弹出4。
var a=document.getElementById("show").getElementsByTagName("li");
for(var i=0;i<a.length;i++){
a[i].onclick=function(index){
return function ()
{
alert(index);
}
}(i);
}
}