js function中返回function 闭包

<html>
<script>
window.onload = function(){
debugger
a();
b();

function a(){
for(var i =1;i<4;i++){
	var p = createElement("a", { href: "javascript:void(0)" });
    p.appendChild(createElement("p", null, null, i));
		//就算onclick事件注册后也会被修改最新的i值
		p.onclick = function(){
			console.log(i);
		}
	document.getElementById('div').appendChild(p);
}
}
function b(){	
for(var i =1;i<4;i++){
	var p1 = createElement("a", { href: "javascript:void(0)" });
    p1.appendChild(createElement("p", null, null, i + 3));
		p1.onclick = function(c){
			return function(){
				console.log(c);
			};
		}(i + 3)
		//一开始写成这样 结果返回值一直都是7
		//p1.onclick = function(){
		//	return function(c){
		//		console.log(c);
		//	}(i + 3);
		//}
	document.getElementById('div').appendChild(p1);
}
}

}

</script>
<head>
</head>
<body>
<div id='div'>
</div>
</body>
</html>

<script>
function createElement(tagName, attributes, styles, text) {
    var v = document.createElement(tagName);
    if (attributes) {
        for (var a in attributes) {
            if (attributes[a]) {
                if (a == "className") {
                    v.className = attributes[a];
                }
                else {
                    v.setAttribute(a, attributes[a]);
                }
            }
        }
    }
    if (styles) {
        for (var s in styles) {
            v.style[s] = styles[s];
        }
    }
    if (text) {
        v.appendChild(document.createTextNode(text));
    }
    return v;
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值