<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>闭包演示</title>
<script src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
window.onload=function(){
function init() {
var pAry = document.getElementsByTagName("p");
cars=["red","green","yellow","blue","pink"];
//console.log(cars[0]);
for( var i=0; i<pAry.length; i++ ) {
pAry[i].onclick = function(ii) {
return function(){
console.log(cars[ii]);
pAry[ii].style.color=cars[ii];
/*pAry[j] = function(num){
return function(){
pAry[num].style.color=cars[j];
};
}(j);*/
}
}(i)
}
}
init()
}
//var aLi = oUl.getElementsByTagName("li");
</script>
</head>
<body > .style.cssText="20px; border:solid 1px #f00;";
<p>产品一</p>
<p>产品二</p>
<p>产品三</p>
<p>产品四</p>
<p>产品五</p>
<div id="w">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</div>
</body>
</html>
这种,你想着每一次i都会循环,实际上i只会打印最后一个数据
例子2
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>闭包演示</title>
<script src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
function init() {
var pAry =$('ul span') ;
var aLi = document.getElementsByTagName("ul");
//console.log(aLi);
cars=["red","green","yellow","blue","pink","orange"];
//console.log(cars[0]);
for( var i=0; i<pAry.length; i++ ) {
pAry[i].onclick = function(ii) {
return function(){
//console.log(cars[ii]);
pAry[ii].style.color=cars[ii];
/*pAry[j] = function(num){
return function(){
pAry[num].style.color=cars[j];
};
}(j);*/
}
}(i)
}
}
init()
})
//var aLi = oUl.getElementsByTagName("li");
</script>
</head>
<body > .style.cssText="20px; border:solid 1px #f00;";
<ul class="ws"><span>产品一</span>
<li class="ww1">产品1_1</li>
<li class="ww2">产品1_1</li>
<li class="ww3">产品1_1</li>
<li class="ww4">产品1_1</li>
<li class="ww5">产品1_1</li>
</ul>
<ul class="ws"><span>产品二</span>
<li class="ww1">产品2_1</li>
<li class="ww2">产品2_1</li>
<li class="ww3">产品2_1</li>
<li class="ww4">产品2_1</li>
<li class="ww5">产品2_1</li>
</ul>
<ul class="ws"><span>产品三</span>
<li class="ww1">产品3_1</li>
<li class="ww2">产品3_1</li>
<li class="ww3">产品3_1</li>
<li class="ww4">产品3_1</li>
<li class="ww5">产品3_1</li>
</ul>
<ul class="ws"><span>产品四</span>
<li class="ww1">产品4_1</li>
<li class="ww2">产品4_1</li>
<li class="ww3">产品4_1</li>
<li class="ww4">产品4_1</li>
<li class="ww5">产品4_1</li>
</ul>
<ul class="ws"><span>产品五</span>
<li class="ww1">产品5_1</li>
<li class="ww2">产品5_1</li>
<li class="ww3">产品5_1</li>
<li class="ww4">产品5_1</li>
<li class="ww5">产品5_1</li>
</ul>
<ul class="ws"><span>产品六</span>
<li class="ww1">产品6_1</li>
<li class="ww2">产品6_1</li>
<li class="ww3">产品6_1</li>
<li class="ww4">产品6_1</li>
<li class="ww5">产品6_1</li>
</ul>
</div>
</body>
</html>
双层闭包循环嵌套