我有2个div对象。我如何将那些包裹在另一个div内?我不能只使用$('.one, .two, .three').wrapAll('<div class="wrap">')
因为所有小方框都是动态的,并且可以有多个小方框。我想将其中的两个包装在一起。
HTML:
<div class="grid">
<div class="grid-item item1"></div>
<div class="grid-item item2 small-box"></div>
<div class="grid-item item3 small-box"></div>
<div class="grid-item item4"></div>
<div class="grid-item item2 small-box"></div>
<div class="grid-item item3 small-box"></div>
</div>
jQuery的:
function small_box_modify(){
var $box = $('.grid > .grid-item');
var $small_box = $('.grid > .small-box');
$small_box.each(function (index) {
var $this = $(this);
if( $this.hasClass('small-box') ){
var $nxt = $this.next('.grid-item');
if( $nxt.hasClass('small-box') ){
// here I want to wrap "$this" and "$nxt" inside new div
// $($this, $nxt).wrapAll('<div class="wrapper">');
}
}
});
}
结果HTML:
<div class="grid">
<div class="grid-item item1"></div>
<div class="wrapper">
<div class="grid-item item2 small-box"></div>
<div class="grid-item item3 small-box"></div>
</div>
<div class="grid-item item4"></div>
<div class="wrapper">
<div class="grid-item item2 small-box"></div>
<div class="grid-item item3 small-box"></div>
</div>
</div>
答案 0 :(得分:2)
您可以这样使用:
if( $nxt.hasClass('small-box') ){
// here I want to wrap "$this" and "$nxt" inside new div
for(var i = 0; i < $nxt.length; i+=2) {
$($this).add($nxt).wrapAll("<div class='wrapper' />");
}
}
答案 1 :(得分:0)
你也可以这样做:
var $set = $('div.grid > .small-box');
for(var i=0, len = $set.length; i < len; i+=2){
$set.slice(i, i+2).wrapAll('<div class="wrapper"/>');
}