当发送到选择标签的值不是使用 knockoutjs 的“全局”时,我正在尝试启用部门选择标签。但由于某种原因,部门选择标签停留在初始启用/禁用状态。动态启用/禁用适用于其他元素,例如文本区域
选择哪个决定另一个的启用/禁用状态
<select data-bind="options: recipientSelector, optionsText: 'name',value: selectedRecipient">
需要禁用/启用的select标签
<select data-bind="options: department_name"></select>
Javascrpt View 模型
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
最佳答案
您可以将 enable
绑定(bind)与您的 selectedRecipient
observable 结合使用,如下所示:
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());
<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>
您还可以使用 visible
绑定(bind)。这可能仍然有点令人困惑,因为第二个 select
仍然显示默认选择。
关于javascript - 动态启用/禁用选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213904/