Knockout.js 使用knockoutjs将类应用于每个第n个模板元素

Knockout.js 使用knockoutjs将类应用于每个第n个模板元素,knockout.js,templating,Knockout.js,Templating,我一直在试验,改造一个现有的项目 我当前的布局具有确定呈现的标记是第一项还是第四项的逻辑 if (index % 4 == 0) addClass('omega'); if (index % 4 == 1) addClass('alpha'); 是否有任何内置的敲除功能可以模板化类似的条件?为您提供一些选项: 在KO中执行foreach时,需要添加$index变量。这将包括在KO 2.1中。拉动请求如下所示: 这里有一个repeat绑定:它使您能够更好地访问实际索引 如果您使用的是obser

我一直在试验,改造一个现有的项目

我当前的布局具有确定呈现的
标记是第一项还是第四项的逻辑

if (index % 4 == 0) addClass('omega');
if (index % 4 == 1) addClass('alpha');
是否有任何内置的敲除功能可以模板化类似的条件?

为您提供一些选项:

  • 在KO中执行
    foreach
    时,需要添加
    $index
    变量。这将包括在KO 2.1中。拉动请求如下所示:

  • 这里有一个
    repeat
    绑定:它使您能够更好地访问实际索引

  • 如果您使用的是observableArray,那么有一种简单的方法可以为每个项目创建索引

它看起来是这样的:

//track an index on items in an observableArray
ko.observableArray.fn.indexed = function() {
   //whenever the array changes, make one loop to update the index on each
   this.subscribe(function(newValue) {
       if (newValue) {
           var item;
           for (var i = 0, j = newValue.length; i < j; i++) {
               item = newValue[i];
               if (!ko.isObservable(item.$index)) {
                  item.$index = ko.observable();
               }
               item.$index(i);      
           }
       }   
   }); 

   this.valueHasMutated(); 
   return this;
};

现在,当操作可观察数组时,它将通过一次项并更正索引。这比在您的
foreach中每次查找每个项目的索引要好。

谢谢,我以前见过这些索引选项。我认为我的问题是,我希望模板根据ObservalArray项删除来更改CSS。只要数组被操作(通过ObservalArray方法),索引就会被重新构建,因此当您删除项时,它会保持索引更新。
this.myArray = ko.observableArray().indexed();