<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document </title>
<script type="text/javascript">
window.onload=function()
{
var em =document.getElementsByTagName("a");
for(var i =0;i<em.length;i++)
{
em[i].onclick=function()
{
alert(i);
alert("you click the"+em[i].innerHTML);
}
}
}
</script>
</head>
<body>
<a>sina </a>
<a>sohu </a>
<a>163 </a>
</body>
</html>
为什么每次alert(i)都是弹出3呢,不解
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document </title>
<script type="text/javascript">
window.onload=function()
{
var em =document.getElementsByTagName("a");
for(var i =0;i<em.length;i++)
{
em[i].onclick=function()
{
alert(i);
alert("you click the"+em[i].innerHTML);
}
}
}
</script>
</head>
<body>
<a>sina </a>
<a>sohu </a>
<a>163 </a>
</body>
</html>
为什么每次alert(i)都是弹出3呢,不解
{
alert(i);
alert("you click the"+em[i].innerHTML);
}})(i)
{
em[i].onclick = function(i) {
return function() {
alert(i);
alert("you click the" + em[i].innerHTML);
// alert("you click the" + this.innerHTML);
};
}(i);
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document </title>
<script type="text/javascript">
window.onload=function()
{
var em =document.getElementsByTagName("a");
for(var i =0;i<em.length;i++)
{
em[i].somevalue=i;
em[i].onclick=function()
{
alert(this.somevalue);
alert(this.innerHTML);
}
}
}
</script>
</head>
<body>
<a>sina </a>
<a>sohu </a>
<a>163 </a>
</body>
</html>
function()
{
alert(i);
alert("you click the"+em[i].innerHTML);
}
中的i都指向的是那同一个i。所以会是最后的i的值3
当然是3了。你的循环再html DOM树一家在完,js马上就运行了。你的变量 i 已经运行并赋值,i运行到了 i = 3 的时候,判断出 i < em.length ,这才推出循环。而且你的代码会报错如下:错误: 'em[...].innerHTML' 为空或不是对象这是因为一共就3个<a>,他们的数组的下标从0开始,应该只有 0、1、2这3个下标。此时你点击的时候i=3,下标越界了。就找不到对象了。=== 结贴,给分 ===
得到满意的答案,立即结贴给分,是一种良好的习惯和美德
得到满意的答案,立即结贴给分,是一种良好的习惯和美德
{
var em =document.getElementsByTagName("a");
var i=0;
for(;i<em.length;i++)
{
em[i].onclick=function()
{
alert(i);//这里始终指向的是变量i,而变量i不属于这个匿名函数,是外部i的一个闭包。所以所有循环的i都指向的是onload里定义的var i.
alert("you click the"+em[i].innerHTML);
}
}
}