将所有元素包装到 :nth-child

Wrap all elements up until :nth-child

本文关键字:nth-child 包装 元素      更新时间:2023-09-26

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

我知道我必须使用:nth-child来计算我想要包装的每一组元素。 我想知道我将如何计算:nth-child并将所有以前的元素(包括:nth-child)包装在与:nth-child匹配的每组元素的div 中。 我假设涉及.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>")
});

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()

嗯,有几种方法,认为我能想到的最简单的方法使用 .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方法:

  • .filter = http://api.jquery.com/filter/
  • .长度 = http://api.jquery.com/length/
  • .wrap = http://api.jquery.com/wrap/