Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - jQuery wrap code after x number of elements

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.

Starting 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>

Required 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 -->

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.

Thanks in advance!!

Al

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this:

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>");
}

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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...