如何从数组中获取单个项目 - jquery

时间:2012-01-11 15:14:02

标签: jquery arrays image

我从JSON文件中提取一系列图像,我有html img,我将图像的src放在:

HTML:

<img class="photos" src="" alt="" />

JS:

for (var i = 0, len = data.length; i < len; i++) {
     var $div = $(".venue:first").clone();
     data.[i].photos;
     $div.find(".photos").attr("src", data[i].photos);
}

[编辑]

JSON: 
comedyData([
    {
        "name": "Broadway Comedy Club",
        "checkinsCount": 2695,
        "tipCount": 36,
        "phone": "2127572323",
        "canonicalUrl": "https://foursquare.com/v/broadway-comedy-club/4afcb158f964a520212522e3",
        "mayor": "David M.",
        "mayor_photo": "https://img-s.foursquare.com/userpix_thumbs/1DFPPSPYD3N2DHBA.jpg",
        "address": "318 West 53rd St, New York, NY 10019",
        "photos": [
            "https://img-s.foursquare.com/derived_pix/0UZLALW0AOLS5NECIKPJQJ15BEUOTFSASYTF3JPWOPO4S130_100x100.jpg",
            "https://img-s.foursquare.com/derived_pix/MMP15NDCGLEC2GKJZEHIVLWLUXJ2IVZHM0DR1Z2K22MQF0PR_100x100.jpg",
            "https://img-s.foursquare.com/derived_pix/RNW1WQQS3BKGMAJT3VV5RJ5XDBQ4FJ1WAGBREWLAWWSM41VB_100x100.jpg",
            "https://img-s.foursquare.com/derived_pix/RI1LT5EUNKFN3303TRI23F0WKCCICOIHNGXTTXDLDEIH454V_100x100.jpg",
            "https://img-s.foursquare.com/derived_pix/0VACIGDCLHHS4FKZO13EDO5SCOCAKGLRE04DSR3B0WT3E0X0_100x100.jpg",
            "https://img-s.foursquare.com/derived_pix/Q2GHCRHSUEUL3AQELVE3KSMP3SMUBDXBWIGXAVSMEKPDVPAQ_100x100.jpg"
        ]
    }

我的问题是它将图像数组放在图像属性中,但我一次只想要一个。我不确定如何从阵列中获取单个图像并将它们放在html图像src中?

1 个答案:

答案 0 :(得分:1)

您可以在function(i, attr)

中提供.attr()
for (var i = 0, len = data.length; i < len; i++) {
     var $div = $(".venue:first").clone();
     data.[i].photos;
     $div.find(".photos").attr("src", function(index, src){
        return data[i].photos[index];
     });
}