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]

解决方案 »

  1.   

    $.each()这个方法会遍历。。和for循环差不多
      

  2.   

    jQuery.each( collection, callback(indexInArray, valueOfElement) )each()方法回调函数中的第一个值是数组结构的索引。
      

  3.   

    这个i其实是each()方法的一个返回值,绑定事件时相当于alert(images[0])、alert(image[1])
      

  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]);
            });
        });
    });
    这段代码,不应该是,先为数组的第一个元素执行 function ,里面创建一个 divNew,添加一个click事件,
    再为第二个元素执行 function...这样子吗?
      

  5.   

    $.each(index, key)
    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>