使用jQuery包装元素组

时间:2014-11-09 10:12:40

标签: javascript jquery

我有一个元素列表,我希望用类HEADER开始将它们分组,如果类是BREAK或最后一个元素,则结束它。

所以下面的代码,

<div class="test">Test 0</div>
<div class="header">Header 1</div>
<div class="test">Test 1</div>
<div class="header">Header 2</div>
<div class="test">Test 2</div>
<div class="test">Test 3</div>
<div class="break">Break 1</div>
<div class="header">Header 3</div>
<div class="test">Test 4</div>
<div class="test">Test 5</div>
<div class="header">Header 4</div>
<div class="test">Test 6</div>
<div class="break">Break 2</div>
<div class="test">Test 7</div>
<div class="header">Header 5</div>
<div class="test">Test 8</div>

会变成,

<div>
    <div class="test">Test 0</div>
    <div class="group">
        <div class="header">Header 1</div>
        <div class="test">Test 1</div>
        <div class="header">Header 2</div>
        <div class="test">Test 2</div>
        <div class="test">Test 3</div>
    </div>
    <div class="break">Break 1</div>
    <div class="group">
        <div class="header">Header 3</div>
        <div class="test">Test 4</div>
        <div class="test">Test 5</div>
        <div class="header">Header 4</div>
        <div class="test">Test 6</div>
    </div>
    <div class="break">Break 2</div>
    <div class="test">Test 7</div>
    <div class="group">
        <div class="header">Header 5</div>
        <div class="test">Test 8</div>
    </div>
<div>

有什么想法吗?提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用wrapAll()方法,如下所示:

&#13;
&#13;
$(".header").each(function() {
  var $group = $(this).nextUntil(".break").addBack();
  if (!$(this).closest(".group").length)
    $group.wrapAll('<div class="group"/>');
});
&#13;
.group {
  background: dodgerblue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Test 0</div>
<div class="header">Header 1</div>
<div class="test">Test 1</div>
<div class="header">Header 2</div>
<div class="test">Test 2</div>
<div class="test">Test 3</div>
<div class="break">Break 1</div>
<div class="header">Header 3</div>
<div class="test">Test 4</div>
<div class="test">Test 5</div>
<div class="header">Header 4</div>
<div class="test">Test 6</div>
<div class="break">Break 2</div>
<div class="test">Test 7</div>
<div class="header">Header 5</div>
<div class="test">Test 8</div>
&#13;
&#13;
&#13;


参考: