在这个例子中,我们有一个房子,里面有很多房间,每个房间里都有很多家具。我希望能够让用户能够切换每个房间家具的可见性(列表可能会很长)。
挑战之一是确保家具是否可见,仅对于他们单击按钮的每个单独房间而言。
这是一个可以玩的 fiddle :http://jsfiddle.net/gztmq4p6/
我的尝试是,对于每个房间,有一个可观察的 bool 值来判断家具是否可见。它不起作用,也没有给出任何错误:
HTML
<tbody data-bind="foreach: rooms">
<tr class="well">
<td valign="top">
<input type="text" data-bind='value: name' />
// Added this
<div> <button class="btn btn-xs btn-info" data-bind='click: toggleFurnitureVisibility'>Toggle Furniture Visibility</button>
<button class="btn btn-xs btn-danger" data-bind='click: $root.removeRoom'>Remove Room</button>
</div>
</td>
<td>
// Added this
<table data-bind="visible: areFurnituresVisible">
<tbody data-bind="foreach: furnitures">
<tr>
<td>
<input type="text" data-bind='value: name' />
</td>
<td>
<input type="text" data-bind='value: size' />
</td>
<td>
<button class="btn btn-xs btn-danger" data-bind='click: $parent.removeFurniture'>Delete Furniture</button>
</td>
</tr>
</tbody>
</table>
<button class="btn btn-success btn-xs" data-bind='click: addFurniture'>Add Furniture</button>
JavaScript
var Room = function(name, furnitures) {
var self = this;
// Default to true
self.areFurnituresVisible = ko.observable(true);
self.toggleFurnitureVisibility = function (room) {
if (self.areFurnituresVisible) {
self.areFurnituresVisible = ko.observable(false);
} else {
self.areFurnituresVisible = ko.observable(true);
}
};
};
最佳答案
如果你有可观察到的:
this.o = ko.observable();
并且您想更新可观察值,您需要使用语法:
this.o(newValue);
就你而言,是
self.areFurnituresVisible(!self.areFurnituresVisible());
关于javascript - 使用 Knockout JS 单击时隐藏和显示特定数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29680027/