jQuery如何用中断来包装兄弟Div

时间:2016-01-14 13:44:48

标签: javascript jquery html

给出以下HTML:

<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<h1>Interruption</h1>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>

我需要的是以下内容:

<div class="wrapper">
  <div class="ms-rteElement-accordion-headline">Headline</div>
  <div class="ms-rteElement-accordion-content">Content</div>
  <div class="ms-rteElement-accordion-headline">Headline</div>
  <div class="ms-rteElement-accordion-content">Content</div>
</div>
<h1>Interruption</h1>
<div class="wrapper">
  <div class="ms-rteElement-accordion-headline">Headline</div>
  <div class="ms-rteElement-accordion-content">Content</div>
</div>

使用jQuery有一个简单的方法吗?我找到了.wrapAll(),但这会给我:

<div class="wrapper">
  <div class="ms-rteElement-accordion-headline">Headline</div>
  <div class="ms-rteElement-accordion-content">Content</div>
  <div class="ms-rteElement-accordion-headline">Headline</div>
  <div class="ms-rteElement-accordion-content">Content</div>
  <div class="ms-rteElement-accordion-headline">Headline</div>
  <div class="ms-rteElement-accordion-content">Content</div>
</div>
<h1>Interruption</h1>

3 个答案:

答案 0 :(得分:3)

使用 .nextUntil 来识别h1出现的位置并使用 .wrapAll

$('div[class^="ms-rteElement"]').each(function(){
	$(this).wrapAll('<div class="wrapper"></div>').nextUntil('h1');
})
.wrapper{
  background:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>
<h1>Interruption</h1>
<div class="ms-rteElement-accordion-headline">Headline</div>
<div class="ms-rteElement-accordion-content">Content</div>

答案 1 :(得分:0)

也许这很有用

$( "h1" ).prevAll('.ms-rteElement-accordion-headline, .ms-rteElement-accordion-content').wrapAll('<div class="wrapper" />');
$( "h1" ).nextAll('.ms-rteElement-accordion-headline, .ms-rteElement-accordion-content').wrapAll('<div class="wrapper" />');

但是你应该将它包含在div

答案 2 :(得分:-1)

你正在寻找这个吗?这是一个非常简单的手风琴Jq accordian