【问题标题】:Knockout.js print index of object in foreachKnockout.js 在 foreach 中打印对象的索引
【发布时间】:2012-04-12 10:00:29
【问题描述】:

这可能很简单,但我似乎不容易找到它。在 knockout.js 中,如何打印使用 foreach 绑定迭代的可观察数组中项目的索引?

【问题讨论】:

标签: knockout.js


【解决方案1】:

以下解决方案可能是迟到的答案。但如果您更喜欢使用viewmodel,则以下解决方案将有助于最新修复。

根据Knockout 3.1.0 及以上的库有简单的解决方法。 index 可以作为辅助参数传递给 arrayForEach

var items = ["Mercedes", "Volvo", "BMW"];

ko.utils.arrayForEach(items, function(item, index) {
    console.log(item + ' ' + index);
});

希望此解决方案可能对某人有所帮助。

【讨论】:

    【解决方案2】:

    knockout 2.1 添加了不错的新选项 $index。 这是示例http://knockoutjs.com/documentation/foreach-binding.html

    【讨论】:

      【解决方案3】:

      你不能。反正不是直接的。我自己使用这个函数来为我的 ObservableArrays 中的对象添加索引属性:

          function indexSubscribe(array) {
              array.subscribe(function() {
                  for (var i = 0, j = array().length; i < j; i++) {
                      var item = array()[i];
                      if (!item.index) {
                          item.index = ko.observable(i);  
                      } else {
                          item.index(i);  
                      }
                  }
              }); 
         };
      

      然后在我的 ViewModel 中,我可以这样做:

      this.whatevers = ko.observableArray();
      indexSubscribe(this.whatevers);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-19
        • 1970-01-01
        • 2017-02-22
        相关资源
        最近更新 更多