Insert
for every 5 elements using Javascript

前端 未结 6 530
悲哀的现实
悲哀的现实 2020-12-31 17:49

I have a simple list of images that is being controlled via a CMS (ExpressionEngine). Like this:


                      
相关标签:
6条回答
  • 2020-12-31 18:21

    You can just create a div for every fith element and move the links into them using the append method:

    var wrapper = $('.wrapper');
    var div;
    $('a', wrapper).each(function(i,e){
        if (i % 5 == 0) div = $('<div/>').addClass('slide').appendTo(wrapper);
        div.append(e);
    });
    

    Demo: http://jsfiddle.net/Guffa/ybrxu/

    0 讨论(0)
  • 2020-12-31 18:22

    You need to use jQuery slice with wrap

    Check this question

    0 讨论(0)
  • 2020-12-31 18:24

    Here's one way:

    Example: http://jsfiddle.net/T6tu4/

    $('div.wrapper > a').each(function(i) {
        if( i % 5 == 0 ) {
            $(this).nextAll().andSelf().slice(0,5).wrapAll('<div class="slide"></div>');
        }
    });
    

    Here's another way:

    Example: http://jsfiddle.net/T6tu4/1/

    var a = $('div.wrapper > a');
    
    for( var i = 0; i < a.length; i+=5 ) {
        a.slice(i, i+5).wrapAll('<div class="slide"></div>');
    }
    
    0 讨论(0)
  • 2020-12-31 18:34

    Try this:

    $(function(){
        var curDiv = null;
        var mainDiv = $("div.wrapper");
        $("span", mainDiv).each(function(i, b){
            if(i%5 == 0) {
                curDiv = $("<div class='slide'/>").appendTo(mainDiv);
            }
            curDiv.append(b);
        });
    });
    
    0 讨论(0)
  • 2020-12-31 18:35

    Use slice() to select the element subset then wrapAll() to wrap the div around them. Here's a function that does that.

    var wrapEveryN = function(n, elements, wrapper) {
       for (var i=0; i< elements.length; i+=n) {
           elements.slice(i,i+n).wrapAll(wrapper);
       }
    }
    
    wrapEveryN( 5, $(".wrapper a"), '<div class="slide"></div>' );
    

    Demo: http://jsfiddle.net/C5cHC/

    Note that the second parameter of slice may go out of bounds, but jQuery seems to handle this automatically.

    0 讨论(0)
  • 2020-12-31 18:36

    I think this would do that:

    var links = $('.wrapper').children();
    for (var i = 0, len = links.length; i < len; i += 5) {
        links.slice(i, i + 5).wrapAll('<div class="slide"/>');
    }
    
    0 讨论(0)
提交回复
热议问题