我在knockout.js中有一个嵌套的foreach循环,我想从内循环内外循环中的当前对象访问一个属性.我该怎么做?
<!-- ko foreach: graduationDateRows -->
<tr>
<td class="center" data-bind="text: CalendarYear"></td>
<!-- ko foreach: $root.graduationDatesHeaders -->
<td class="center" data-bind="text: /* !here! */"></td>
<td></td>
<!-- /ko -->
</tr>
<!-- /ko -->
Run Code Online (Sandbox Code Playgroud)
RP *_*yer 27
您可以使用$parent访问一个范围级别.因此,从您的内部循环中,您可以使用parent来访问在您的循环中循环的当前项目graduationDateRows
Sta*_*bko 15
您甚至可以在绑定中使用和别名来遍历完全不相关的数组.$parentasforeach
请考虑以下示例:
var VM = function(){
this.rows = ['one','two','three'];
this.cols = [1,2,3,4,5];
}
ko.applyBindings(new VM());
Run Code Online (Sandbox Code Playgroud)
<table border="1">
<tr>
<th></th>
<!-- ko foreach: cols -->
<th data-bind="text: $data"></th>
<!-- /ko -->
</tr>
<!-- ko foreach: {data: rows, as: 'row'} -->
<tr>
<th data-bind="text:row"></th>
<!-- ko foreach: {data: $parent.cols, as: 'col'} -->
<td data-bind="text:row + '/' + col"></td>
<!-- /ko -->
</tr>
<!-- /ko -->
</table>
Run Code Online (Sandbox Code Playgroud)
要从内循环中的当前对象访问外部循环中的属性,您可以使用$parent.property_name.
例如:
<ul id="salesInfo" data-bind="foreach : salesInfo ">
<li class="department">
<a href="#" data-bind="text: name" />
<ul id="salesDept" data-bind="foreach: years">
<li class="years">
<a href="#" data-bind="text: year, click:function(data, event) { $root.yearClicked(year,$parent.name,data) }" />
</li>
</ul>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
salesInfo数组的示例对象:
{
"id" : "0",
"name" : "Human Resources",
"years" : [
{ "year" : "2012", "values" : [250000,350000,150000,220000,450000,180000] }
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23155 次 |
| 最近记录: |