使用jQuery将连续列表项包装在不同的组中 [英] Wrapping consecutive list items in separate groups using jQuery
本文介绍了使用jQuery将连续列表项包装在不同的组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由CMS导出的无序列表,需要识别具有.sub类的< li>
元素并将它们包装在< ul>
。
I have an unordered list exported by a CMS and need to identify <li>
elements that have the class .sub and wrap them in a <ul>
.
我尝试了 wrapAll()
方法但是找到所有< li class =sub>
元素并将它们包装在一个< ul>
中。我需要它来维持单独的分组。
I have tried the wrapAll()
method but that finds all <li class="sub">
elements and wraps them in one <ul>
. I need it to maintain seperate groupings.
导出的代码如下:
<ul>
<li></li>
<li></li>
<li></li>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
<li></li>
<li></li>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
<li></li>
</ul>
我需要它:
<ul>
<li></li>
<li></li>
<li></li>
<ul>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
</ul>
<li></li>
<li></li>
<li></li>
<ul>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
</ul>
<li></li>
<li></li>
</ul>
我们非常感谢任何帮助。
Any help would be greatly appreciated.
推荐答案
- 使用
。每个
遍历所有.sub
元素。 - 忽略其父级有类的元素
wrapped
,使用hasClass()
- 使用
nextUntil(:not(.sub))
选择所有连续的子元素(使用.andSelf()
)。
给定的第一个参数表示:当元素不匹配时停止向前看.sub
。 -
wrapAll
- Use
.each
to walk through all.sub
elements. - Ignore elements whose parent has class
wrapped
, usinghasClass()
- Use
nextUntil(:not(.sub))
to select all consecutive sub elements (include itself using.andSelf()
).
The given first parameter means: Stop looking forward when the element does not match.sub
. wrapAll
演示: http://jsfiddle.net/8MVKu/
为了完整起见,我在< li>中包装了一套
而不是简单的< li>
元素。 < ul> ...< / ul>< / li> < ul>
。
Demo: http://jsfiddle.net/8MVKu/
For completeness, I have wrapped the set of <li>
elements in <li><ul>...</ul></li>
instead of a plain <ul>
.
代码:
$('.sub').each(function() {
if ($(this.parentNode).hasClass('wrapped')) return;
$(this).nextUntil(':not(.sub)').andSelf().wrapAll('<li><ul class="wrapped">');
});
$('ul.wrapped').removeClass('wrapped'); // Remove temporary dummy
这篇关于使用jQuery将连续列表项包装在不同的组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文