我有以下基本结构。我需要能够单独切换每个表的可见性。类似乎不起作用,因为它会用同一类切换所有类。项目数量未知,因此外部 div 数量未知,而且我不知道 id,因为它不是唯一的。
<div data-bind="foreach: items">
// Other pieces of data here...
<button data-bind="click: myToggleFunction">Hide/Show</button> // This could be image, link or whatever to trigger toggle
<table> // Need to toggle tables individually
//Rows and columns here bound to the elements of each "item"
</table>
</div>
只是不确定如何让它确定它尝试切换哪个表。
最佳答案
See a Demo
我喜欢为 Knockout 项目提供方便的toggle
功能。这是一个。
ko.observable.fn.toggle = function () {
var obs = this;
return function () {
obs(!obs())
};
};
然后我们可以创建具有可见属性的对象。在这些对象内定义所有表数据。
function Item() {
var self = this;
self.visible = ko.observable(true);
}
我们的 ViewModel 包含这些项目的数组。如果您需要的话,它就在 fiddle 上。
当我们到达 HTML 时,我们可以在点击处理程序中设置 visible.toggle()
,这会切换我们的 visible
可观察对象。当我们的 Item
的 visible
属性为 true 时,我们的 table
也必然是可见的。
<div data-bind="foreach: items">
<div>
<button data-bind="click: visible.toggle()">Toggle</button>
<table data-bind="visible: visible">
...
</table>
</div>
</div>
关于jquery - knockout : Toggle table visibility inside foreach div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559842/