假设我在页面上有以下三个带有唯一ID的div
<div id="product-id-001"></div>
<div id="product-id-002"></div>
<div id="product-id-003"></div>
我需要根据div的id添加以下图像元素的代码是什么?
<div id="product-id-001">
<img src="images/product-id-001-1.jpg"></img>
<img src="images/product-id-001-2.jpg"></img>
<img src="images/product-id-001-3.jpg"></img>
</div>
<div id="product-id-002">
<img src="images/product-id-002-1.jpg"></img>
<img src="images/product-id-002-2.jpg"></img>
<img src="images/product-id-002-3.jpg"></img>
</div>
<div id="product-id-003">
<img src="images/product-id-003-1.jpg"></img>
<img src="images/product-id-003-2.jpg"></img>
<img src="images/product-id-003-3.jpg"></img>
</div>
感谢您的任何提示。
答案 0 :(得分:1)
$('div[id^=product]').each(function(index, elem) {
for(var i = 1; i < 4; i++) {
$('<img>', {
src: '/images/' + elem.id + i
}).appendTo(this);
}
});
演示:http://www.jsfiddle.net/9S9Av/
(您需要Firebug或其他DOM检查器才能查看结果)
答案 1 :(得分:0)
来自jQuery docs:
“.append()方法将指定的内容作为jQuery集合中每个元素的最后一个子元素插入”
所以:
$('#product-id-001").append('<img src="images/product-id-001-1.jpg"></img>');
等...
答案 2 :(得分:0)
// Select all elements with an id beginning with product-id:
var $productContainers = $('[id^=product-id]');
// Loop through the matched elements and append the images:
$productContainers.each(function () {
var $this = $(this),
productId = $this.attr('id'),
numImages = 3,
extension = '.jpg';
// Create and append the images based on the configuration above. Note that this
// assumes that each product have three valid images.
for (var i = 1; i <= numImages; i++)
{
var $image = $('<img alt="" />').attr('src', 'images/'+productId+'-'+i+extension);
$image.appendTo($this);
}
});