【发布时间】:2012-10-11 20:18:45
【问题描述】:
我有一系列 DIV,根据大小分配了 .big 或 .small。它们需要以两个或三个为一组进行包装。实际上,分配的空间中只能容纳两个.bigs。
如果两个.big DIV 彼此相邻存在,则应将它们以两个为一组进行包装。否则,DIV 应该以三个为一组进行包装。
请让我知道我做错了什么以及如何让它发挥作用。下面是一个 cmets 示例,说明包裹应该在哪里断裂。下面是我在 jQuery 中尝试过的,以及 link to jsFiddle。
<div class="big post">big</div>
<div class="big post">big</div>
<!-- should be wrap break -->
<div class="big post">big</div>
<div class="big post">big</div>
<!-- should be wrap break -->
<div class="big post">big</div>
<div class="small post">small</div>
<div class="big post">big</div>
<!-- should be wrap break -->
<div class="small post">small</div>
<div class="small post">small</div>
<div class="big post">big</div>
<!-- should be wrap break -->
<div class="big post">big</div>
<div class="small post">small</div>
<!-- should be wrap break -->
我认为下面的if 工作得很好,但是else 破坏了所有的东西。
$('.post').each(function() {
if ( $(this).hasClass('big') && $(this).next('.post').hasClass('big') ) {
var allElements = $(this).next().andSelf(),
WRAP_BY = 2;
for (var i = 0; i < allElements.length; i += WRAP_BY) {
allElements.slice(i, i + WRAP_BY).andSelf().wrapAll('<div class="flowed" />');
}//for
}//if
else {
// the else breaks all the things
var allElements = $(this).next().andSelf(),
WRAP_BY = 3;
for (var i = 0; i < allElements.length; i += WRAP_BY) {
allElements.slice(i, i + WRAP_BY).andSelf().wrapAll('<div class="flowed" />');
}//for
}//else
});//each
【问题讨论】:
标签: javascript jquery wrapall