我有 2 个选择列表,我想同步索引,所以当第一个的索引为 1 时,第二个的索引为 1,依此类推。
这是我的 html。
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<div>
<select id="selLight" data-bind="options: $root.ddlLight, value: ddlLightSelected"></select>
<select id="selAction" data-bind="options: $root.ddlAction, value: ddlActionSelected"></select>
</div>
和 javascript...
var ViewModel = function() {
var self = this;
self.ddlLight = ko.observableArray(["RED", "AMBER", "GREEN"]);
self.ddlAction = ko.observableArray(["STOP", "READY", "GO"]);
self.ddlLightSelected = ko.observable();
self.ddlActionSelected = ko.observable();
self.ddlLightSelected.subscribe(function (event) {
document.getElementById("selAction").selectedIndex =
self.ddlLight.indexOf(self.ddlLightSelected());
});
self.ddlActionSelected.subscribe(function (event) {
document.getElementById("selLight").selectedIndex =
self.ddlAction.indexOf(self.ddlActionSelected());
});
};
ko.applyBindings(new ViewModel());
我有一个确切的问题...
http://jsfiddle.net/phykell/2vUTw/
编辑:我在使用 jsfiddle 时遇到了一些问题,所以这是一个 jsbin... http://jsbin.com/ilomer/4/
...这里是重现问题的方法:
- 运行 jsFiddle
- 从灯中选择绿色(操作将变为开始)3. 从操作中选择停止(灯应变为红色但实际上没有)
最佳答案
问题是这行代码:
document.getElementById("selAction").selectedIndex = self.ddlLight.indexOf(self.ddlLightSelected());
您是在直接更改 DOM,不允许 Knockout 启动可观察模式。
如果您想要更改某些内容,请始终更改 ko.observable
,而不是 JavaScript 变量或 DOM。 Knockout 将识别更改,并因此更改 DOM 本身。解决方案是:
self.ddlLightSelected.subscribe(function (event) {
var index = self.ddlLight.indexOf(self.ddlLightSelected());
self.ddlActionSelected(self.ddlAction()[index]); // Update the Observable, not the DOM
});
self.ddlActionSelected.subscribe(function (event) {
var index = self.ddlAction.indexOf(self.ddlActionSelected());
self.ddlLightSelected(self.ddlLight()[index]); // Update the Observable, not the DOM
});
关于javascript - knockout.js 更新选择列表不会在第一次更改时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14520067/