所以我使用 KnockoutJS 来填充 <select>
使用选项并获取选择的值。
<select data-bind="enable: cols1().length > 0, options: cols1(), optionsText: 'name', value: jCol1" id="col1"></select>
变量cols1
保存具有简单格式 { name: "name" }
的对象只是因为它需要成为我在页面上执行的其他一些操作的对象。有没有办法从该元素的数据绑定(bind)外部设置选择的值?
最佳答案
绑定(bind)的value
部分表示:
将对 jCol1
中 cols1
中的项目的引用存储在 jCol1
如果您想从 UI 外部更改选择,则必须将 jCol1
设置为 cols1
数组中的值。如果您尝试将其设置为其他值,knockout 会立即将其重置为第一个值。切换下面示例中注释的代码行以查看是否发生这种情况:
var ViewModel = function() {
this.options = ko.observableArray([
{ name: "Item 1" },
{ name: "Item 2" },
{ name: "Item 3" }
]);
this.selection = ko.observable();
this.selection.subscribe(function(newValue) {
console.log(newValue)
});
this.changeSelectionFromOutside = function() {
// This does not work because knockout does not do a
// deep comparison of objects
// this.selection({ name: "Item 3" });
// This _does_ work, because it references one of the
// options objects
this.selection(this.options()[2]);
}.bind(this);
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: options, value: selection, optionsText: 'name'"></select>
<button data-bind="click: changeSelectionFromOutside">
Set option 3
</button>
现在,您还可以选择仅存储您选择的字符串 ID(或其他基元)。这使得从外部设置事物变得更容易,因为您只需要 ID 而不是对实际项目的引用:
var ViewModel = function() {
this.options = ko.observableArray([
{ name: "Item 1" },
{ name: "Item 2" },
{ name: "Item 3" }
]);
this.selection = ko.observable();
this.selection.subscribe(function(newValue) {
console.log(newValue)
});
this.changeSelectionFromOutside = function() {
this.selection("Item 3");
}.bind(this);
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: options, value: selection, optionsText: 'name', optionsValue: 'name'"></select>
<button data-bind="click: changeSelectionFromOutside">
Set option 3
</button>
关于javascript - 在 Knockout 中设置动态填充选择的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38791407/