我需要拆分每2个li并将它们附加到div [英] I need to split every 2 li's and append them to a div

查看:51
本文介绍了我需要拆分每2个li并将它们附加到div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用列表

 <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添加类的原因是这是一个在Business中创建的动态菜单催化剂,我可以使用任何建议来处理这种情况的最佳方法。

The reason I can't add classes to the li's is that this is a dynamic menu created in Business Catalyst, I could use any advice as to the best way to deal with this situation.

Best Tara

Best Tara

推荐答案

示例: 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) 每秒获取< li> 从第一个开始

  • 每个() (docs) 迭代在他们身上

  • next() (docs) 获得下一个< li>

  • add() (docs) 将当前的一个添加到下一个(所以你有1& 2,3& 4等组)

  • wrapAll() (docs) 用新的包装器包装它们。

  • eq() (docs) 从集合中获取第一个

  • nearest() (docs) 遍历最近的(新创建的) < div> ancestor

  • unwrap() (docs) 删除旧的< ul>

    • nth-child-selector(docs) gets every second <li> starting with the first
    • each()(docs) iterates over them
    • next()(docs) gets the next <li>
    • add()(docs) adds the current one to the next (so you have groups of 1&2, 3&4, etc.)
    • wrapAll()(docs) wraps them with the new wrappers.
    • eq()(docs) gets the first one from the set
    • closest()(docs) traverses up to the closest (newly created) <div> ancestor
    • unwrap()(docs) removes the old <ul>
    • 编辑:修改了我处理奇数< li> 元素的答案。

      Modified my answer to deal with an odd number of <li> elements.

      这篇关于我需要拆分每2个li并将它们附加到div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆