如何设置不同的<a href=""> and <img src=""/> dynamically in divs with same class name?

时间:2016-03-14 07:57:35

标签: javascript jquery html

I have an array of objects(each that are made up of image link and link). As I access each of them I would like to make a new div each time and add a different image link and link.

<div class="igo_product"
    <a href>
        link1
        <img class="igo_product_image" src="imglink1">
</div>
<div class="igo_product"
    <a href>
        link2
        <img class="igo_product_image" src="imglink2">
</div>
<div class="igo_product"
    <a href>
        link3
        <img class="igo_product_image" src="imglink3">
</div>

Currently the only way I can place different images and links is by creating different class names by concatenating indexes at the end each time.

$.each(items, function (index, value) {
    $(".igo_boxbody").append('<div class="igo_product' + index + '"<a><img class="igo_product_image' + index + '"></a></div>')
    $(".igo_product" + index + "a").attr('href', value["link"].toString());
    $(".igo_product_image" + index).attr('src', value["image_link"] );
});

However, $(".igo_product" + index + "a").attr('href', value["link"].toString()); does not correctly set my href...I'm assuming it's my way I'm concatenating the class, index, and a but I'm slightly stuck on what else I can do. Also, is there a better way to do this? I would rather keep the class name the same so that I can apply styles to all these classes easier.

3 个答案:

答案 0 :(得分:1)

这个怎么样:

$.each(items, function (index, value) {
                $(".igo_boxbody").append('<div class="igo_product"<a href="'+value["link"].toString()+'"><img class="igo_product_image" src="'+value["image_link"]+'"></div>');
             });

答案 1 :(得分:1)

有一个错误:

$(".igo_boxbody").append('<div class="igo_product' + index + '"<a><img class="igo_product_image' + index + '"></a></div>')
 //-----------------------------------------------------------^---no closing of div >

所以改为:

$(".igo_boxbody").append('<div class="igo_product' + index + '"><a><img class="igo_product_image' + index + '"></a></div>')

应该这样做:

$.each(items, function (index, value) {
    var el = '<div class="igo_product"' + index 
             + '><a href="'+value["link"]
             +'"><img class="igo_product_image' + index 
             + '" src="'+value["image_link"]+'"></a></div>'
    $(".igo_boxbody").append(el);
});

答案 2 :(得分:1)

绝不是我打算暗示以下更好,但只是提到选项:你可以使用jquery在DOM之外创建html对象(例如$('<div>')创建一个新的div)并设置它们的属性/通过这些对象的属性/类/等(在将它们添加到DOM之前)。 优点是您不必深入研究字符串以捕获那些结束标记:

$('.igo_boxbody').append(items.map(function(value, index){
    return  $('<div>').addClass('igo_product').append(
        $('<a>').attr('href', value.link).append(
          $('<img>').attr('src', value.image_link).addClass('igo_product_image' + index)
     )
  );
}));

Fiddle