【问题标题】:How can I access index variable from outer foreach loop in knockout如何在淘汰赛中从外部 foreach 循环访问索引变量
【发布时间】:2016-06-05 14:16:23
【问题描述】:

我可以访问外部 foreach 循环的索引直到 2 级,但在第三级,它不起作用。以下代码,如何在最里面的foreach循环中获取第一个foreach循环的索引:

<!-- ko foreach: Clauses-->
<!-- ko foreach: ClauseRepeatingSections -->
<!-- ko foreach: RepeatingSectionElements -->
    How to get Clauses item index here?

【问题讨论】:

标签: knockout.js foreach


【解决方案1】:

基本上要升2级

$parentContext.$parentContext.$index()

请看下面的例子 https://jsfiddle.net/wgsdddtj/

var viewModel = function () {
	var self = this;
  
  var Product = function (name, products) {
  	var pSelf = this;
    pSelf.name = ko.observable(name);
    pSelf.items = ko.observableArray(products);
  };
  
  self.products = ko.observableArray([
  	new Product("product1", [
    	new Product("product1a", [
      	new Product("product1aI", []),
        new Product("product1aII", [])
      ]),
      new Product("product1b", [
      	new Product("product1bI", []),
        new Product("product1bII", [])
      ])
    	]),
    new Product("product2", [
    	new Product("product2a", [
      	new Product("product2aI", [])
      ]),
      new Product("product2b", [
      	new Product("product2bI", [])
      ])
    	])
  ]);
};

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: { data: products, as: 'level1' }">
  <li>
    <span data-bind="text: name"></span>
    <ul data-bind="foreach: { data: items, as: 'level2' }">
      <li>
        <span data-bind="text: name"></span>
        <ul data-bind="foreach: { data: items, as: 'level3' }">
          <li>
            <span data-bind="text: name"></span> - lvl1: 
            <span data-bind="text: $parentContext.$parentContext.$index()"></span> - lvl2:
            <span data-bind="text: $parentContext.$index()"></span> - lvl3:
            <span data-bind="text: $index()"></span>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

【讨论】:

    【解决方案2】:

    为了使代码更全面,我建议像这样使用 foreach:

    <!-- ko foreach: { data: Clauses, as: 'clause' } -->
        <!-- ko foreach: { data: clause.ClauseRepeatingSections, as: 'repeatingSection' } -->
            <!-- ko foreach: { data: repeatingSection.RepeatingSectionElements, as: 'element' } -->
                // each of the current level is now stored in the variable you called it in 'as' parameter. To access the current clause:
                clause.anyPropertyOrFunction
            <!-- /ko -->
        <!-- /ko -->
    <!-- /ko -->
    

    【讨论】:

    • 对不起,如果我们谈论的是访问子句的属性,你是完全正确的,但是如果我们想要 $index() observable,我们必须回答我的答案,$parentContext.$parentContext.$index()跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2017-12-12
    • 2012-09-25
    • 2012-11-11
    相关资源
    最近更新 更多