我需要分割每两个 li 并将它们附加到 div

2024-02-28

我有一个通用列表:

<ul>
    <li>list item1</li>
    <li>list item2</li>
    <li>list item3</li>
    <li>list item4</li>
    <li>list item5</li>
    <li>list item6</li>
</ul>

但我想做的是:

<div class="list">
    <ul>
        <li>list item1</li>
        <li>list item2</li>
    </ul>
</div>

<div class="list">
    <ul>
        <li>list item3</li>
        <li>list item4</li>
    </ul>
</div>

<div class="list">
    <ul>
        <li>list item5</li>
        <li>list item6</li>
    </ul>
</div>

我无法向其中添加类的原因li https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li这是一个动态菜单,创建于商业催化剂 https://en.wikipedia.org/wiki/Business_Catalyst。处理这种情况的最佳方法是什么?


Example: http://jsfiddle.net/jBYqt/2/ http://jsfiddle.net/jBYqt/2/

$('ul > li:nth-child(2n-1)').each(function() {
    $(this).next().add(this).wrapAll('<div class="list"><ul></ul></div>');
}).eq(0).closest('div').unwrap();
  • nth-child-selector(docs) http://api.jquery.com/nth-child-selector/ gets every second <li> starting with the first
  • each()(docs) http://api.jquery.com/each/ iterates over them
  • next()(docs) http://api.jquery.com/next/ gets the next <li>
  • add()(docs) http://api.jquery.com/add/ adds the current one to the next (so you have groups of 1&2, 3&4, etc.)
  • wrapAll()(docs) http://api.jquery.com/wrapAll/ wraps them with the new wrappers.
  • eq()(docs) http://api.jquery.com/eq/ gets the first one from the set
  • closest()(docs) http://api.jquery.com/closest/ traverses up to the closest (newly created) <div> ancestor
  • unwrap()(docs) http://api.jquery.com/unwrap/ removes the old <ul>

EDIT:修改了我的答案以处理奇数<li>元素。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我需要分割每两个 li 并将它们附加到 div 的相关文章

随机推荐