I have four images in a div like and adding the src to each image dynamically with jQuery in a loop as follows:
jQuery("<img>",{src: BASE_URL+image_url)
do the image tag will like this:
<img src="site_url/media/catalog/size_images/1.png"/>
<img src="site_url/media/catalog/size_images/2.png"/>
<img src="site_url/media/catalog/size_images/3.png"/>
<img src="site_url/media/catalog/size_images/4.png"/>
now i want to add a different id to each image dynamically so the tag will be as follows:
<img id="1" src="site_url/media/catalog/size_images/1.png"/>
<img id="1" src="site_url/media/catalog/size_images/1.png"/>
<img id="1" src="site_url/media/catalog/size_images/1.png"/>
<img id="1" src="site_url/media/catalog/size_images/1.png"/>
答案 0 :(得分:0)
Try like this,
$("<img>",{src: BASE_URL+image_url, id: $('img').length});
However, you will need to append this image to document body, so that you get new id next time you call this code.
It can be,
$("<img>",{src: BASE_URL+image_url, id: $('img').length}).appendTo('#target');
Hope this help.
答案 1 :(得分:0)
for (x=0;x<$(target_div).children('img').length;x++){
var thisImg = $(target_div).children('img')[x];
thisImg.id = x;
thisImg.src = BASE_URL+image_url;
thisImg.alt = '';
}
其中'target_div'是包含img标签的div。 确保包含有效html的'alt'属性。
答案 2 :(得分:0)
您可以使用jQuery动态添加每个图片的src和唯一ID,用于这样的循环:
for (var i = 0; i < 4; i++) {
$('div').append($('<img>',{id: "id" + i, src: BASE_URL+image_url}));
}