如何使用 knockout js 根据另一个下拉列表的选择在下拉列表中设置所选值

How do I set the selected value in a dropdown based on the selection of another dropdown using knockout js

我正在尝试根据某人 select 在另一个下拉列表中的内容,将下拉列表中的 selection 设置为特定的 selection。我正在使用 knockout js,这里是我需要更新值的 select 的 knockout 代码。

self.availableSex = ko.observableArray([
    new selectionOption("Male", "M"),
    new selectionOption("Female", "F")
]);
self.selectedSex = ko.observable();

和html部分

<select data-bind="options: availableSex,
     optionsText: 'name',
     value: selectedSex,
     optionsCaption: 'Select'" required>
</select>

我想要 select 根据另一个下拉列表选择男性或女性。我知道如何获取这些值,但我似乎无法根据其他下拉菜单将其设置为我希望设置的值。

感谢您的帮助。我希望这一切都有意义。

您可以使用 subscribe。只需在页面上搜索(向底部)

[编辑]

根据评论我更新了示例

你会做的是

self.others = ko.observableArray([1,2]);
self.selectedOther = ko.observable();

self.availableSex = ko.observableArray([
    new selectionOption("Male", "M"),
    new selectionOption("Female", "F")
]);
self.selectedSex = ko.observable();
self.selectedSex.subscribe(function(newValue){
    //newValue should be of type selectionOption
    if(newValue.value === "M"){ 
      self.selectedOther(1);
    }else{
     self.selectedOther(2);
    }
    //set other observable value
});

我在这里假设 selectionOption 看起来像这样:

var selectionOption = function(name, value){
    this.name = name;
    this.value = value;
};

因此我为什么要这样做 newValue.value

作为另一个说明,我不是 100% 确定 knockout 如何比较复杂的对象,所以如果你必须这样做 self.selectedOther(some complex Object) 你可能不会得到想要的行为。为了安全起见,我通常会查找源代码,并传入相同的引用。