可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have multiple divs like this:
<div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="large"></div> <div class="large"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div>
I want to select every 4 .small divs to wrap in another div so it's like this:
<div class="box"> <div class="small"></div> <div class="small"></div> <div class="small"></div> <div class="small"></div> </div>
As you can see from the first example, there can be more than 4 adjacent ones, but I still want to group every 4 .small divs.
Any idea would be much appreciated. Thanks!
回答1:
Here is how I've done it in the past.
jsFiddle.
I chunk the selected elements into chunks of a desired length and then call wrapAll()
on the sub-selection.
Just for the hell of it, here is how you'd do it without jQuery...
jsFiddle.
Of course, for old browsers that don't support document.querySelectorAll()
or document.getElementsByClassName()
, replace the element selecting code with...
var divs = document.getElementsByTagName('div'), smallDivs = []; for (var i = 0, length = divs.length; i < length; i++) { if ((' ' + divs[i].className + ' ').indexOf(' small ') >= 0) { smallDivs.push(divs[i]); } }
jsFiddle.
回答2:
You use slice
or gt()
and lt()
See example below
$(".small").slice(4,10).wrapAll('<div class"smallWrapper"></div>');
Or
$(".small:gt(5):lt(10)").wrapAll('<div class"smallWrapper">
jsfiddle demo