我可以访问外部foreach循环的索引到2级,但在第三层,它是不工作的。下面的代码,如何在最内部的foreach循环中获取第一个foreach循环的索引:
<!-- ko foreach: Clauses-->
<!-- ko foreach: ClauseRepeatingSections -->
<!-- ko foreach: RepeatingSectionElements -->
How to get Clauses item index here?发布于 2016-02-23 20:23:11
基本上,要达到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>
发布于 2016-02-24 15:42:38
为了使代码更全面,我建议使用以下方式:
<!-- 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 -->https://stackoverflow.com/questions/35582701
复制相似问题