标签:length 两种 lease edit pre styles element blog var
<span style="font-family:Microsoft YaHei;"><html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>闭包演示</title>
<script type="text/javascript">
function init() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i<pAry.length; i++ ) {
pAry[i].onclick = function() {
alert(i);
}
}
}
</script>
</head>
<body onload="init();">
<p>产品一</p>
<p>产品二</p>
<p>产品三</p>
<p>产品四</p>
<p>产品五</p>
</body>
</html> </span>
解决方案有两种。
1、将变量 i 保存给在每一个段落对象(p)上
<span style="font-family:Microsoft YaHei;"> function init() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i<pAry.length; i++ ) {
pAry[i].i = i;
pAry[i].onclick = function() {
alert(this.i);
}
}
} </span>
<span style="font-family:Microsoft YaHei;"> function init2() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i<pAry.length; i++ ) {
(pAry[i].onclick = function() {
alert(arguments.callee.i);
}).i = i;
}
} </span>
标签:length 两种 lease edit pre styles element blog var
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10658536.html