我想要实现的目标:一个菜单栏,它将显示不同的div数据。
我有什么:
<table>
<tr>
<td data-bind="foreach: menuItems">
<button data-bind="text: name, click: navigate" class="buttonTD"></button>
</td>
</tr>
</table>
<div id='1'></div>
<div id='2'></div>
viewModel:
this._tabs = ko.observableArray([
{ id: '1', name: "Compliance", navigate: 'tab2Visible: ko.observable(false)', style: 'active' },
{ id: '2', name: "ITC ", navigate: 'tab3Visible: ko.observable(false)', style: 'inactive' },
{ id: '3', name: "Check", navigate: 'tab4Visible: ko.observable(false)', style: 'inactive' },
{ id: '4', name: "Check Champion", navigate: 'tab5Visible: ko.observable(false)', style: 'inactive' },
{ id: '5', name: "Tech", navigate: 'tab6Visible: ko.observable(false)', style: 'inactive' },
{ id: '6', name: "Comm", navigate: 'tab7Visible: ko.observable(false)', style: 'inactive' },
{ id: '7', name: "Order", navigate: 'tab8Visible: ko.observable(false)', style: 'inactive' },
{ id: '8', name: "Order Rejected", navigate: 'tab9Visible: ko.observable(false)', style: 'inactive' },
{ id: '9', name: "Cancel", navigate: 'tab10Visible: ko.observable(false)', style: 'inactive' }
]);
this.menuItems = this._tabs;
当我点击按钮1向我显示div 1时,当我点击button2向我显示div3等时,该数组如何改变。
抱歉不清楚。
答案 0 :(得分:1)
拥有一个基于id保存当前选项卡的变量会更好。更新和跟踪多个bool变量会使代码难以维护。此外,您需要创建一个不是字符串的点击事件。
你可能想要这样的东西:
<table>
<tr>
<td data-bind="foreach: menuItems">
<button data-bind="text: name, click: $parent.onTabClick" class="buttonTD"></button>
</td>
</tr>
</table>
<div data-bind="visible: visibleTab() == 1">Tab 1</div>
<div data-bind="visible: visibleTab() == 2">Tab 2</div>
<!-- etc... -->
<div data-bind="visible: visibleTab() == 9">Tab 9</div>
然后在ViewModel中:
this.visibleTab = ko.observable(1);
this.menuItems = ko.observableArray([
{ id: '1', name: "Compliance", style: 'active' },
{ id: '2', name: "ITC ", style: 'inactive' },
{ id: '3', name: "Check", style: 'inactive' },
{ id: '4', name: "Check Champion", style: 'inactive' },
{ id: '5', name: "Tech", style: 'inactive' },
{ id: '6', name: "Comm", style: 'inactive' },
{ id: '7', name: "Order", style: 'inactive' },
{ id: '8', name: "Order Rejected", style: 'inactive' },
{ id: '9', name: "Cancel", style: 'inactive' }
]);
this.onTabClick = (item) => {
this.visibleTab(item.id);
};