动态启用/禁用选择标记

Dynamically enable/disable select tag

本文关键字:选择 启用 动态      更新时间:2023-09-26

当send-to-select标记的值不是使用knockoutjs的"global"时,我正在尝试启用department select标记。但由于某些原因,department select标记被固定在初始启用/禁用状态。动态启用/禁用适用于其他元素,例如文本区域

选择确定另一个的启用/禁用状态

<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());

屏幕截图"自定义"选项启用"部门"选择元素

您可以将enable绑定与您的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绑定。这可能仍然有点令人困惑,因为第二个select仍然有点显示默认选择。

您可以将enable与视图模型中已计算的一起使用

<select data-bind="options: department_name, enable: disableSelects"></select>

参见演示

这将向选择标记添加一个禁用的属性。它的视觉效果将取决于您的UI样式/框架。