每个函数都可以从数组中创建img元素

时间:2014-05-04 12:40:38

标签: javascript jquery html

我需要一些支持。我有一个数组:

var imageArr = [
    { someobject: '..', anotherobject: '..', img: 'SourceOfFirstImg.jpg'}, 
    { someobject: '..', anotherobject: '..', img: 'SourceOfSecondImg.jpg'},
    // 100 times
]

我想要做的是创建一个.each()函数来创建<img>元素,用每个链接src填充它们并将它们附加到div。如果有一个简单的JS方式,我也不需要each()

我该怎么做?

4 个答案:

答案 0 :(得分:3)

您可以使用map method创建要追加的图像元素数组:

$('.somediv').append($.map(imageArr, function(o){
  return $('<img>', { src: o.img });
}));

答案 1 :(得分:1)

var imageArr = [
                { someobject: '..', anotherobject: '..', img: 'SourceOfFirstImg.jpg'}, 
                { someobject: '..', anotherobject: '..', img: 'SourceOfSecondImg.jpg'},
                // 100 times
               ]
for (var i = 0; i < imageArr.length; i++) {
     var img = $('<img class="foo" >'); 
     img.attr('src', imageArr[i].img);
     $('body').append(img);

};

答案 2 :(得分:1)

最简单的,我建议:

var imageArray = [{
    'alt': 'Alt text',
        'src': 'http://placekitten.com/200/200',
        'title': 'Title text'
}, {
    'alt': 'More alt text',
        'src': 'http://lorempixel.com/200/200',
        'title': 'Yet another title attribute'
}],
    target = document.body,
    img;

imageArray.forEach(function(a){
    img = document.createElement('img');
    for (var prop in a) {
        if (a.hasOwnProperty(prop)) {
            img[prop] = a[prop];
        }
    }
    target.appendChild(img);
});

JS Fiddle demo

已编辑以使用已发布的imageArr OP

var imageArr = [{
    someobject: '..',
    anotherobject: '..',
    img: 'SourceOfFirstImg.jpg'
}, {
    someobject: '..',
    anotherobject: '..',
    img: 'SourceOfSecondImg.jpg'
}],
    target = document.body,
    img;

imageArr.forEach(function (a) {
    img = document.createElement('img');
    img.src = a.img;
    target.appendChild(img);
});

JS Fiddle demo

参考文献:

答案 3 :(得分:0)

试试这个:

var imageArr = [
    { someobject: '..', anotherobject: '..', img: 'http://www.clipartbest.com/cliparts/Rcd/K5B/RcdK5Bbgi.png'}, 
    { someobject: '..', anotherobject: '..', img: 'http://www.clipartbest.com/cliparts/Rcd/K5B/RcdK5Bbgi.png'},
]
var div = document.createElement("div");
for(i = 0; i< imageArr.length; i++)
{
   var img = document.createElement("img");
   img.setAttribute("src",imageArr[i].img);
   div.appendChild(img);
}
alert(div.innerHTML);

以下是 Demo