【问题标题】:Appending ascending images based on the id of parent div根据父 div 的 id 附加升序图像
【发布时间】:2011-06-25 09:36:23
【问题描述】:

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

感谢任何提示。

【问题讨论】:

    标签: javascript jquery image append


    【解决方案1】:
    // 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);
       }
    });
    

    【讨论】:

    • 这行不通。您需要将$this.val('id') 替换为this.id$this.attr('id'),并且您需要将.val('src') 替换为.attr('src')
    • 谢谢。只是匆忙写了。
    【解决方案2】:
    $('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 检查器才能看到结果)

    【讨论】:

    • 天哪,太美了!你的贝宝地址是什么?
    • @user427687: andreas.goebel@typeofnan.com :o)
    【解决方案3】:

    来自jQuery docs

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

    所以:

    $('#product-id-001").append('<img src="images/product-id-001-1.jpg"></img>');
    

    等等……

    【讨论】:

      猜你喜欢
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      相关资源
      最近更新 更多