jQuery在x个元素之后包装代码 [英] jQuery wrap code after x number of elements

查看:95
本文介绍了jQuery在x个元素之后包装代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含任意数量LI的UL。我正在尝试创建一些jQuery代码,它将解析原始UL并在每5个原始LI之后包装UL和另一个LI。

I have a UL that contain any number of LIs. I am trying to create some jQuery code that will parse the original UL and wrap a UL and another LI after every 5 of the original LIs.

启动HTML:

<ul id="original_ul">
    <li class="original_li">..</li>
    <li>..</li>
    <li>..</li>
    <li>..</li>
    <li>..</li>
    <li>..</li>
    <li>..</li>
    <li>..</li>
    <li>..</li>
    <li>..</li>
</ul>

必填HTML:

<ul id="processed_ul">

    <li class="new_wrap_li">

        <ul class="new_wrap_ul">

            <li class="original_li">..</li>
            <li>..</li>
            <li>..</li>
            <li>..</li>
            <li>..</li>

        </ul><!-- end new wrap ul -->

    </li><!-- end new wrap li -->

    <li class="new_wrap_li">

        <ul class="new_wrap_ul">

            <li class="original_li">..</li>
            <li>..</li>
            <li>..</li>
            <li>..</li>
            <li>..</li>

        </ul><!-- end new wrap ul -->

    </li><!-- end new wrap li -->

</ul><!-- end processed ul -->

我一直在使用.each函数来浏览LI并将它们附加到新处理过的ul保持在临时div ...现在我只需要在每5个LI周围包装新的LI和UL。

I've been using the .each function to go through the LIs and append them to the new processed ul held inside a temp div... now I just need to wrap the new LI and UL around every 5 LIs.

提前致谢!!

Al

推荐答案

你可以这样做:

var lis = $("#original_ul li");
for(var i = 0; i < lis.length; i+=5) {
  lis.slice(i, i+5)
     .wrapAll("<li class='new_wrap_li'><ul class='new_wrap_ul'></ul></li>");
}

这使它们保持在同一个 #original_ul 元素,但如果有必要,您可以更改ID。除了顶部的ID < ul>

This keeps them in the same #original_ul element, but you could just change the ID if that's necessary. This approach generates the exact output html you have in the question aside from the ID on the top <ul>

这篇关于jQuery在x个元素之后包装代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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