我开始学习Knockout,但我遇到了一些麻烦。我有一个可观察的数组,它有一些按钮。我需要: 示例:
我点击第二个按钮'lock'并可见第二个跨度'lock',隐藏第二个跨度'unlock'。这应该是一个“锁定”功能。
等
我不知道......怎么做?
请帮助!
这是我的模特:
function newNames() {
var self = this;
self.btnClick = ko.observable(true);
self.newName = ko.observable();
self.names = ko.observableArray([
{id: 1, name: 'Name1'},
{id: 2, name: 'Name2'},
{id: 3, name: 'Name3'}
]);
self.lock = function () {
self.btnClick(false);
};
self.unlock = function () {
self.btnClick(true);
};
self.clickRename = function () {
for (var i = 0; i < self.names().length; i++) {
if (self.btnClick() == false) {
} else {
self.names.replace(self.names()[i], {
name: self.newName()
});
}
}
};
};
ko.applyBindings(new newNames());
这是html:
<div class="form-group">
<input type="text" class="form-control" data-bind="value: newName">
<button type="button" class="btn" data-bind="click: clickRename">
RENAME
</button>
</div>
<div class="group" data-bind="foreach: names">
<div class="form">
<!-- hidden: $parent.btnClick() == false, visible: $parent.btnClick() == true
$parent.btnClick() == false -->
<span id="span1" data-bind="visible: $parent.btnClick">unlock</span>
<span id="span2" data-bind="hidden: $parent.btnClick() == true, visible: $parent.btnClick() == false">lock</span>
<input type="text" class="form-control" data-bind="value: name">
<button type="button" class="btn" data-bind="click: $root.lock">
LOCK
</button>
<button type="button" class="btn" data-bind="click: $root.unlock">
UNLOCK
</button>
</div>
</div>
答案 0 :(得分:0)
你可以试试这个。 无论如何,你可以改进代码,在对象数组上添加带有按钮标签的计算属性。
我已将值传递给点击按钮,其中设置相应的新属性锁定,从而显示/隐藏相应的范围。
<div class="form-group">
<input type="text" class="form-control" data-bind="value: newName">
<button type="button" class="btn" data-bind="click: clickRename"> RENAME </button>
</div>
<div class="group" data-bind="foreach: names">
<div class="form">
<span id="span1" data-bind="visible: lock() == true">unlock</span>
<span id="span2" data-bind="visible: lock() == false">lock</span>
<input type="text" class="form-control" data-bind="value: name">
<button type="button" class="btn" data-bind="click: function(data, event) { $parent.lock(!lock(), data, event); }">
<span data-bind="visible: lock() == false">LOCK</span>
<span data-bind="visible: lock() == true">UN-LOCK</span>
</button>
</div>
</div>
<script>
function newNames() {
var self = this;
self.btnClick = ko.observable(true);
self.newName = ko.observable();
self.names = ko.observableArray([
{ id: 1, name: 'Name1', lock: ko.observable(false) },
{ id: 2, name: 'Name2', lock: ko.observable(false) },
{ id: 3, name: 'Name3', lock: ko.observable(false) }
]);
self.lock = function (value, data, event) {
console.log(data);
data.lock(value);
};
self.clickRename = function () {
for (var i = 0; i < self.names().length; i++) {
if (self.btnClick() == false) {
} else {
self.names.replace(self.names()[i], {
name: self.newName()
});
}
}
};
};
ko.applyBindings(new newNames());
</script>