var images = ["1", "2", "3", "4"];
$(function(){
$.each(images, function (i) {
var divNew = $('<div style="width:20px;height:10px; background-color:blue;float:left;margin:2px"></div>'); $(divNew).click(function () {
alert(images[i]);
});
});
});我想知道,点击每个新建的层 为什么可以得到 不同的 images[i]
$.each(images, function (i) {
var divNew = $('<div style="width:20px;height:10px; background-color:blue;float:left;margin:2px"></div>'); $(divNew).click(function () {
alert(images[i]);
});
});
});
这段代码,不应该是,先为数组的第一个元素执行 function ,里面创建一个 divNew,添加一个click事件,
再为第二个元素执行 function...这样子吗?
index是指 当前元素位于array中的索引
key是指当前元素
each就相当于封装的for语句参考下
<!DOCTYPE HTML>
<html>
<head>
<meta charset="gb2312" />
<title></title>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<script>
function $(el){
return typeof el == 'string' ? document.getElementById(el) : el;
}
function $t(name, cot){
cot = cot || document;
return cot.getElementsByTagName(name);
}
function makeArray( obj ){
var arr = [];
for ( var i = 0, len = obj.length; i < len; i++ ){
arr.push(obj[i]);
}
return arr;
}
Array.prototype.each = function(fn){
for ( var i =0, len = this.length; i < len; i++ ){
fn.call( null, i, this[i] );
}
}
var objs = $t('div');
var arr = makeArray(objs);
arr.each(function(i, k){
k.onclick = function(){
alert(i)
}
})
</script>
</body>
</html>