<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>