Insert
for every 5 elements using Javascript

前端 未结 6 527
悲哀的现实
悲哀的现实 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: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"), '
    ' );

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

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

提交回复
热议问题