javascript - 动态启用/禁用选择标签

标签 javascript html knockout.js html-select

当发送到选择标签的值不是使用 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/

相关文章:

Javascript/JQuery 故障排除

php - 为什么我没有滚动条?

knockout.js - KnockoutJS - 嵌套数据,加载子项

knockout.js - Knockout JS 删除不起作用

javascript - 为什么 POST 请求在 iOS Safari 中不起作用?

javascript - 如何在 JavaScript 中读取所选元素的值

JavaScript 正则表达式 : Replace curly braces

html - 需要帮助在 HTML 中设置两列布局

javascript - 将一个 div 拖到另一个 div 并在我结束时更改另一个 div 的大小

javascript - 使用 Knockout 时是否应该在模型或 View 模型中加载数据