淘汰赛由4号组成

时间:2014-01-31 13:38:46

标签: javascript knockout.js

有一个现有的数组,我希望它在由div包装的组中显示4:

<div class="swiper-wrapper" data-bind="foreach: roomCards">
     <!-- ko if: ($index == 0 || ($index + 1) % 4) -->
     <div class="swiper-slide">
     <!-- /ko -->
     <div>
        data
     <div>
     <!-- ko if: ($index == 0 || ($index + 1) % 4) -->
     </div>
     <!-- /ko -->
</div>

Ko如果不起作用,因为它只打开标签(破坏DOM) 但这不起作用。

需要这样的东西:

<div class="swiper-wrapper">
    <div class="swiper-slide">
        <div>
           data
        </div>
        <div>
           data
        </div>
        <div>
           data
        </div>
        <div>
           data
        </div>
    </div>
    <div class="swiper-slide">
        <div>
           data
        </div>
        <div>
           data
        </div>
        <div>
           data
        </div>
        <div>
           data
        </div>
    </div>
...
</div>

任何解决方案?

2 个答案:

答案 0 :(得分:1)

为ViewModel提供相应级别的分组:

self.roomCards = ko.observableArray([1,2,3,4,5,6,7,8]);

self.roomCardsGrouped = ko.computed(function(){
    return self.roomCards().chunk(4);
});

上面提到的chunk方法来自this answer(归功于@ninjagecko),摘录如下:

Array.prototype.chunk = function(chunkSize) {
    var array=this;
    return [].concat.apply([],
        array.map(function(elem,i) {
            return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
        })
    );
}

无论如何,请将您的视图更新为以下内容:

<div class="swiper-wrapper" data-bind="foreach: roomCardsGrouped">
     <div class="swiper-slide">
         <!-- ko foreach: $data -->
         <div>
             <span data-bind="text: $data"></span>
         </div>
         <!-- /ko -->
     </div>
</div>

请参阅this fiddle了解演示。

答案 1 :(得分:1)

您需要像$index那样展开$index(),数据div也有2个开始标记,而不是一个结束标记:

<div class="swiper-wrapper" data-bind="foreach: roomCards">
     <!-- ko if: ($index() == 0 || ($index() + 1) % 4) -->
     <div class="swiper-slide">
     <!-- /ko -->
     <div>
        data
     </div> 
     <!-- ko if: ($index() == 0 || ($index() + 1) % 4) -->
     </div>
     <!-- /ko -->
</div>