【问题标题】:Can you get a subset of elements in jQuery as per a grouping amount?您可以根据分组数量在 jQuery 中获取元素的子集吗?
【发布时间】:2009-04-17 03:57:14
【问题描述】:

假设我有 5 个强元素,我想使用 jQuery 将它们包装在 div 元素中,以 2 个为一组。

例子:

<!--original markup-->
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>

变成

<!-- new markup -->
<div>
    <strong>I AM STRONG</strong>
    <strong>I AM STRONG</strong>
</div>
<div>
    <strong>I AM STRONG</strong>
    <strong>I AM STRONG</strong>
</div><div>
    <strong>I AM STRONG</strong>
</div>

最好的方法是什么?我尝试了一些事情,但它们有问题。强元素不能有固定的高度。此外,这些元素仅作为示例。

我将如何编写一个 jQuery 循环来做到这一点?

谢谢

编辑 没有固定数量的元素。

【问题讨论】:

    标签: javascript jquery loops


    【解决方案1】:

    我可能一次只循环两个,边走边包装每一对......

    var elems = $("strong");
    for (var i=0; i<elems.length; i+=2)
    {
      elems.slice(i,i+2)   // split off a pair
        .wrapAll("<div>"); // wrap it
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 :odd 来选择所有其他元素,然后使用 .prev 来获取偶数元素。

      $('strong:odd').each(function(){
        var divElement = $('<div></div>').append($(this).prev(), $(this));
        // Now add the divElement to a new container?
      });
      

      【讨论】:

        猜你喜欢
        • 2018-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-27
        • 2012-02-02
        • 1970-01-01
        相关资源
        最近更新 更多