0

我很难弄清楚这一点,但我相信这很简单。

我知道我必须用它:nth-child来计算我想要包装的每一组元素。我想知道如何计算:nth-child和包装所有以前的元素,包括:nth-child在 div 中匹配的每组元素:nth-child。我假设有一个.each()参与。

代码的布局如下:

<div class="wrapper"> 
<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>

<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>


<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>


<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>

更新 尝试了这段代码,它似乎给了我想要的结果,但在 16 处停止。

  $(".wrapper").each( function () {
$(this).children(":lt(16)").wrapAll("<div></div>")
});
4

2 回答 2

1

jQuery 的.each()函数有一个内置的index——所以我们可以利用它来选择每 16 个元素。

$("div.wrapper").children().each(function(i){
    if(i % 16 == 0 && i != 0){
        // We get the elements we need to wrap, but they're going to be in reverse order (thanks to .prevAll())
        var elementsToWrap = $(this).prevAll().not('.wrap2');
        var temp = [];
        for(var j=0; j < elementsToWrap.size(); j++){
            // Reverse the objects selected by placing them in a temporary array.
            temp[(elementsToWrap.size()-1) - j] = elementsToWrap.eq(j)[0];
        }
        // Wrap the array back into a jQuery object, then use .wrapAll() to add a div around them
        $(temp).wrapAll('<div class="wrap2" />');
    }
});

​演示 http://jsfiddle.net/CRz7E/1/

如果您想单独包装每个元素 - 而不是作为一个组,那么您不需要反转选择,您可以使用.wrap()

于 2012-06-12T22:14:30.223 回答
0

有几种方法,我认为最简单的方法是使用.filter 我将简单地向您展示一个简单的示例,也许您可​​以修改您的问题以获得更具体的答案。

假设您的 HTML 很简单,如下所示:

<body>
    <style type="text/css">
        .goober {
            background: #ffa;
            color: #696969;
        }
    </style>

    <div>1</div>
    <p>1</p>
    <div>2</div>
    <p>2</p>
    <div>3</div>
    <p>3</p>
    <div>4</div>
    <p>4</p>​
</body>

假设你想用“goober”类将所有 p 元素包装在一个 div 中。当然,除了最后一个。

然后你可以 jQuery 如下:

$(function() {
    // here i use .filter and in the return i recall the same jQuery array 
    // object that i'm filtering in order to compare the index value to 
    // its length
    $("p").filter(function(i) { 
        return i != $("p").length-1; 
    }).wrap('<div class="goober" />'); // then of course our wrapper
});​

使用的 jQuery 方法:

于 2012-06-12T21:53:47.220 回答