我希望使用jQuery来选择p
标签,这些标签是具有某个类hdr
的范围的祖父元素,然后我想要包装该标签及其所有标签#39 ;兄弟姐妹直到下一个p标签,它是hdr
类的父母,依此类推。
我遇到的问题是第二个和第三个包装器以及包含内容的内容最终会嵌套在前一个包装器中,而不是一个接一个地打印每个包装器。
我的初始加价:
$('.main .hdr').parents('p').each(function() {
$(this).nextUntil($(this)).addBack().wrapAll('<div class="wrapper" />');
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<p><strong><span class="hdr">Heading #1</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p><strong><span class="hdr">Heading #2</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p><strong><span class="hdr">Heading #3</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
</div>
&#13;
当前输出:
<div class="main">
<div class="wrapper">
<p><strong><span class="hdr">Heading #1</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<div class="wrapper">
<p><strong><span class="hdr">Heading #2</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<div class="wrapper">
<p><strong><span class="hdr">Heading #3</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
</div>
</div>
</div>
</div>
&#13;
期望的输出:
<div class="main">
<div class="wrapper">
<p><strong><span class="hdr">Heading #1</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
</div>
<div class="wrapper">
<p><strong><span class="hdr">Heading #2</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
</div>
<div class="wrapper">
<p><strong><span class="hdr">Heading #3</span></strong></p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
<p>Some paragraph text</p>
</div>
</div>
&#13;
答案 0 :(得分:2)
这样的事情,将选择内容传递给nextUntil
,甚至只传递p:has(.hdr)
,而不是$(this)
var elems = $('.main p:has(.hdr)');
elems.each(function() {
$(this).nextUntil(elems).addBack().wrapAll('<div class="wrapper" />');
});