gpt4 book ai didi

javascript - 将多个输入绑定(bind)到可观察数组中的同一个变量(Knockout.JS)

转载 作者:行者123 更新时间:2023-11-29 20:54:51 26 4
gpt4 key购买 nike

我想将多个输入绑定(bind)并更改为同一个变量(以便它们始终一起更改为相同的值),但我无法弄清楚这一点。我的代码:

        $(function () {
var AppVm = function () {
this.people = ko.observableArray([
{ firstName: 'Bert', lastName: 'Bertington' },
{ firstName: 'Charles', lastName: 'Charlesforth' },
{ firstName: 'Denise', lastName: 'Dentiste' }
]);
};
vm = new AppVm();
ko.applyBindings(vm);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr><th>First name</th><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td>
<input type="text" data-bind="textInput: firstName"/>
</td>
<td>
<input type="text" data-bind="textInput: firstName"/>
</td>
</tr>
</tbody>
</table>

它最初在两个文本输入中加载相同的值,但是当我更改其中一个时,另一个不会更新。如何同时更新它们?

最佳答案

正如 Jason Spake 在评论中所说:

Your properties must be observable in order to update with knockout. Making the whole array observable doesn't make the individual properties observable. ObservableArrays only react to changes in the array size.

因此,您需要在 observableArray 中使用 ko.observable() 来检测更改:

$(function () {
var AppVm = function () {
this.people = ko.observableArray([
{ firstName: ko.observable('Bert'), lastName: ko.observable('Bertington') },
{ firstName: ko.observable('Charles'), lastName: ko.observable('Charlesforth') },
{ firstName: ko.observable('Denise'), lastName: ko.observable('Dentiste') }
]);
};
vm = new AppVm();
ko.applyBindings(vm);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<thead>
<tr><th>First name</th><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td>
<input type="text" data-bind="textInput: firstName"/>
</td>
<td>
<input type="text" data-bind="textInput: firstName"/>
</td>
</tr>
</tbody>
</table>

现在,当您更改左侧输入中的值时,in 也会同时更改右侧输入中的值。

关于javascript - 将多个输入绑定(bind)到可观察数组中的同一个变量(Knockout.JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com