当使用knockoutjs发送到select标签的值不是“global”时,我正在尝试启用department select标签。但由于某种原因,部门选择标签停留在初始启用/禁用状态。动态启用/禁用适用于其他元素,例如textarea的
选择确定其他
的启用/禁用状态的选项 <select data-bind="options: recipientSelector, optionsText: 'name',value: selectedRecipient">
需要禁用/启用的选择标记
<select data-bind="options: department_name"></select>
Javascrpt ViewModel
var SendMessageModel = function() {
var self = this;
this.to = ko.observableArray();
this.to_all = ko.observable();
this.title = ko.observable();
this.message = ko.observable();
this.recipientSelector = [
{ recipient: "global", name: "To All" },
{ recipient: "custom", name: "Custom" }
];
this.selectedRecipient = ko.observable();
this.department_name = ['CSE', 'ECE', 'EE'];
self.disableSelects = ko.pureComputed(function () {
return self.selectedRecipient().recipient == "global";
});
};
ko.applyBindings(new SendMessageModel());
Screenshot "Custom" option enables "Department" select element
答案 0 :(得分:1)
您可以将enable
绑定与selectedRecipient
可观察对象结合使用,如下所示:
var SendMessageModel = function() {
var self = this;
this.to = ko.observableArray();
this.to_all = ko.observable();
this.title = ko.observable();
this.message = ko.observable();
this.recipientSelector = [
{ recipient: "global", name: "To All" },
{ recipient: "custom", name: "Custom" }
];
this.selectedRecipient = ko.observable();
this.department_name = ['CSE', 'ECE', 'EE'];
self.disableSelects = ko.pureComputed(function () {
return self.selectedRecipient().recipient == "global";
});
};
ko.applyBindings(new SendMessageModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="
options: recipientSelector,
optionsText: 'name',
value: selectedRecipient"></select>
<select data-bind="
options: department_name,
enable: selectedRecipient().recipient === 'custom'"></select>
&#13;
您还可以使用visible
绑定。这可能仍然有点令人困惑,因为第二个select
仍显示默认选择。
答案 1 :(得分:0)
您可以将enable
与已在视图模型中使用的计算值一起使用:
<select data-bind="options: department_name, enable: disableSelects"></select>
请参阅demo
这会将select属性添加到select标记。视觉效果如何取决于您的UI样式/框架。