例子:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>闭包演示</title>
<style type="text/css">
div {
background: gray;
margin:5px;
}
</style>
<script type="text/javascript">
function init() {
var list = document.getElementsByTagName("div");
for ( var i = 0; i < list.length; i++) {
var div = list[i];
div.onclick = function() {
alert(div.innerHTML);
};
list[i].onmousemove = function() {
this.style.backgroundColor = "green";
}
list[i].onmouseout = function() {
this.style.backgroundColor = "gray";
}
}}</script></head><body onload="init();"><div>0</div><div>1</div><div>2</div><div>3</div><div>4</div></body></html>
每次都弹出最后一次的结果4。
解决方案1:
function daili(element ) {
this.clickFunc = function() {
alert(" record" + element.innerHTML);
}
}
function init(){
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
list[i].onmousemove = function() {
this.style.backgroundColor = "green";
}
list[i].onmouseout = function() {
this.style.backgroundColor = "gray";
}
list[i].onclick = new daili(list[i]).clickFunc;
}
}
解决方案2:
function init(){
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
list[i].onmousemove = function() {
this.style.backgroundColor = "green";
}
list[i].onmouseout = function() {
this.style.backgroundColor = "gray";
}
var div = list[i];
function(div){
div.onclick = function(){
alert(div.innerHTML);
}
}
}
}
function init(){
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
list[i].onmousemove = function() {
this.style.backgroundColor = "green";
};
list[i].onmouseout = function() {
this.style.backgroundColor = "gray";
};
var div = list[i];
// 匿名写法1
(function(o){
o.onclick = function(){
alert(o.innerHTML);
};
})(div);
}
}
解决方案4:
function init(){
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
list[i].onmousemove = function() {
this.style.backgroundColor = "green";
};
list[i].onmouseout = function() {
this.style.backgroundColor = "gray";
};
// 匿名写法 2
(function(o){
var o = list[i];
o.onclick = function(){
alert(o.innerHTML);
};
})();
}
}
方案5:
function init() {
var list = document.getElementsByTagName("div");
for ( var i = 0; i < list.length; i++) {
var div = list[i];
div.onclick = function() {
alert(this.innerHTML);
};
div.onmousemove = function() {
this.style.backgroundColor = "green";
};
div.onmouseout = function() {
this.style.backgroundColor = "gray";
};
}
}