Javascript 基于父div的id追加升序图像

Javascript 基于父div的id追加升序图像,javascript,jquery,image,append,Javascript,Jquery,Image,Append,假设我在一个页面上有以下三个具有唯一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

假设我在一个页面上有以下三个具有唯一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>

谢谢你的提示。

来自:

“append()方法将指定的内容作为jQuery集合中每个元素的最后一个子元素插入”

因此:

$('#product-id-001”)。追加('';
等等。

//选择id以产品id开头的所有元素:
var$productContainers=$(“[id^=productid]”);
//循环遍历匹配的元素并附加图像:
$productContainers.each(函数(){
变量$this=$(this),
productId=$this.attr('id'),
numImages=3,
扩展名='.jpg';
//根据上面的配置创建并附加映像
//假设每个产品都有三个有效图像。
对于(var i=1;i
$('div[id^=product]')。每个(函数(索引,元素){
对于(变量i=1;i<4;i++){
$('
演示


(您需要Firebug或其他DOM检查器才能查看结果)

这不起作用。您需要将
$This.val('id')
替换为
This.id
$This.attr('id')
,并且需要将
.val('src')
替换为
.attr('src'))
谢谢。只是匆匆写下。天哪,太漂亮了!你的贝宝地址是什么?@user427687:andreas。goebel@typeofnan.com:o)
$('#product-id-001").append('<img src="images/product-id-001-1.jpg"></img>');
// 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);
   }
});
$('div[id^=product]').each(function(index, elem) {
   for(var i = 1; i < 4; i++) {
       $('<img>', {
          src:    '/images/' + elem.id + i
       }).appendTo(this);
   }
});