I need to wrap three divs into one, but that group of three divs is repeating itself several times in code. Maybe my HTML will explain:
<div class="one" />
<div class="two" />
<div class="three" />
<div class="one" />
<div class="two" />
<div class="three" />
What I'm trying to achieve is this:
<div class="wrap">
<div class="one" />
<div class="two" />
<div class="three" />
</div>
<div class="wrap">
<div class="one" />
<div class="two" />
<div class="three" /开发者_如何学JAVA>
</div>
This is wrapping everything into one div:
$('.one, .two, .three').wrapAll('<div class="wrap" />')
How can I get the groups wrapped separately?
$(function(){
var all = $('.one, .two, .three');
for(i=0; i<all.length; i+=3){
all.slice(i,i+3).wrapAll('<div class="wrap" />');
}
});
See it in action: http://jsbin.com/uqosa/
By the way, <div class="one" />
didn't work for me on Firefox, I had to close them with </div>
.
Try this:
$('div.one').each(function() {
var wrap = $(this).wrap('<div class="wrap"></div>').parent();
wrap.next('div.two').appendTo(wrap);
wrap.next('div.three').appendTo(wrap);
});
This will work:
$(function() {
var $ones = $('div.one');
var $twos = $('div.two');
var $threes = $('div.three');
$ones.each(function(idx) {
$('<div class="wrap"></div>')
.append($ones.eq(idx))
.append($twos.eq(idx))
.append($threes.eq(idx))
.appendTo('body');
});
});
In my head this should work:
$('.one').each(function() {
var wrap = $('<div>').addClass('wrap'), two = $(this).next(), three = $(two).next();
$(this).after(wrap).appendTo(wrap)
two.appendTo(wrap), three.appendTo(wrap)
});
$.fn.matchUntil = function(expr) {
var match = [];
this.each(function(){
match = [this];
for ( var i = this.nextSibling; i; i = i.nextSibling ) {
if ( i.nodeType != 1 ) { continue; }
if ( $(i).filter(expr).length > 0 ) { break; }
match.push( i );
}
});
return this.pushStack( match );
};
usage:
$(".one").each( function() {
$(this).matchUntil(".one").wrapAll("<div class='wr'></div>");
})
it's just modified version of http://docs.jquery.com/JQuery_1.2_Roadmap#.nextUntil.28.29_.2F_.prevUntil.28.29, which doesn't seem to work with new jQuery.
精彩评论