【发布时间】:2015-03-22 23:15:36
【问题描述】:
我有一个下拉列表(选择控件)使用 options、optionsValue、optionsText 和 optionsCaption 绑定绑定到一个可观察数组。
如果我选择了一个选项,然后将其删除,则下拉菜单会选择第一项。我希望它将选定的值设置为未定义,而不必向可观察数组添加一个空项。
这是一个简单的例子:
<select data-bind="value: selectedItemValue, options: items, optionsValue: 'value', optionsText: 'text', optionsCaption: ''"></select>
<button type="button" data-bind="click: selectLast">Select Last</button>
<button type="button" data-bind="click: removeLastItem">Remove Last</button>
var viewmodel = function () {
var self = this;
this.items = ko.observableArray();
this.selectedItemValue = ko.observable(null);
this.selectLast = function () {
self.selectedItemValue(
self.items()[self.items().length - 1].value);
};
this.removeLastItem = function () {
self.items.pop();
};
this.items.push({
value: "item1",
text: "First item"
});
this.items.push({
value: "item2",
text: "Second item"
});
this.items.push({
value: "item3",
text: "Third item"
});
};
var vm = new viewmodel();
ko.applyBindings(vm);
- 单击“选择最后一项”按钮或手动选择下拉菜单中的最后一项
- 单击“删除最后一个”按钮
- 结果:第一个项目被选中
实现我想要的行为的最佳方法是什么?
【问题讨论】:
标签: javascript html knockout.js