【问题标题】:JQuery to add divs to list of imagesJQuery 将 div 添加到图像列表中
【发布时间】:2011-01-19 02:19:35
【问题描述】:

嘿,我有一个需要用 div 包装的图像列表,以便每三个图像都在一个新的 div 中。第一个 div 必须从头开始,并在关闭和打开下一个 div 之前继续接下来的三个图像。最终的 HTML 应该如下所示:

<div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>

我知道这应该与第 n 个子选择器有关,但到目前为止,我只能选择单个元素,而不能一次选择三个。

【问题讨论】:

  • 你已经给了 na final,但首字母是什么?

标签: javascript jquery jquery-selectors css-selectors


【解决方案1】:

嗯,

$('img:nth-child(3n)').each(function(){
    $(this).prevAll('img').andSelf().wrapAll('<div/>');
});

demo

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    var imgListLength = $imageList.length, // assuming $imageList is your jQuery object
        tmpArray = $imageList.toArray(),
        newHtml = '';
    
    for (var i = 0; i < imgListLength; i = i + 3) {
      newHtml += '<div>';
      newHtml += tmpArray[i] + tmpArray[i + 1] + tmpArray[i + 2];
      newHtml += '</div>';
    }
    
    $('body').append(newHtml);
    

    【讨论】:

      【解决方案3】:

      假设这些图像位于 ID 为 container 的容器中,您可以这样做:

      示例: http://jsfiddle.net/c2nQH/

      var imgs = $('#container > img');
      
      imgs.each(function(i) {
                // If we're on a multiple of 3...
          if (i % 3 == 0) {
                    // ...take a slice of it and the next two, and wrap them.
              imgs.slice(i, i + 3).wrapAll('<div></div>');
          }
      });
      

      【讨论】:

      • 嘿伙计们,我使用了 patrick dw 示例,它成功了。谢谢!
      • @msegreto:很高兴它成功了。如果这是您最终使用的解决方案,请记住单击此答案左侧的大复选标记。谢谢。 :o)
      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多