【问题标题】:.wrapAll() based on adjacent siblings' class and.wrapAll() 基于相邻兄弟的类和
【发布时间】: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

http://jsfiddle.net/natejones/UvsZE/

【问题讨论】:

    标签: javascript jquery wrapall


    【解决方案1】:

    首先 - 你需要从函数返回,如果元素,已经包装,

    其次,我不明白为什么你需要在else 中循环for(你可以使用$.nextAll() 来获取当前之后的所有兄弟)

    here代码

    $('.post').each(function() {
        //return if already wrapped!
        if ($(this).parent().hasClass('flowed')) {
            return;
        }
        var WRAP_BY = 3;
        if ($(this).hasClass('big') && $(this).next('.post').hasClass('big')) {
            WRAP_BY = 2;
        }
        var allElements = $(this).nextAll().andSelf();
        allElements.slice(0, WRAP_BY).wrapAll('<div class="flowed" />');
    }); //each​
    

    【讨论】:

    • 我也更喜欢让 $(this) 成为一个变量,然后你就可以像 var $this=$(this) 这样的函数中使用它;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2012-03-08
    • 2016-05-13
    相关资源
    最近更新 更多