<!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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
<div id="test">
<span>0</span>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
</body>
</html>
<script type="text/javascript">
window.addEventListener("load",init,false);
function init(){
spans=$("test").getElementsByTagName("span");
for(var i=0;i<spans.length;i++)
{
spans[i].onclick=function(){
alert(i);
}
}
}
function $(id){
return document.getElementById(id);
}
</script>为什么单击0 1 2 3弹出的警告框都是4?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
嗯,这是很常见的闭包问题
在for循环中循环每一个元素,为它们的click事件分别绑定一个函数
这个函数会 alert 出 i 的值,这个时候只绑定了函数而没有立即执行,直到for 循环结束,这个时候 i 的值为 4
当你点击第 j 个元素时候,这个时候执行了绑定函数,然而这个时候 i 的值已经变成了 4,所以无论你点击哪一个都是 alert 4