gpt4 book ai didi

javascript - 基于 ID Knockoutjs 的两个下拉选项绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 19:56:09 25 4
gpt4 key购买 nike

我有以下内容:

     <select data-bind="options: animals, value: optionsValue: 'ID', optionsText: 'Name'" />

self.animals = ko.mapping.fromJS([
{"Name": "Tamed": , "ID": "1" },
{"Name": "Wild": , "ID": "2" },
]);

self.wildOrTamed = ko.mapping.fromJS([
{ "Name": "Cat", "ID": "1" },
{ "Name": "Lion", "ID": "2" },
{ "Name": "Cat": "1" },
{ "Name": "Tiger", "ID": "2" }]);

我希望有 2 个下拉菜单,供动物选择驯养或野生动物,然后根据该情况更改我的 wildOrTamed 下拉列表以使用指定的 ID 显示野生动物或驯养动物。

注意:这是动态的,因此可能有其他类型的动物......

谁能帮我解决这个问题。

谢谢

最佳答案

尝试使用computed observable 。看看 fiddle http://jsfiddle.net/aravindbaskaran/6w4N8/

<select data-bind="options: animalTypes, value: animalType, optionsValue: 'ID', optionsText: 'Name'"></select>
<select data-bind="options: animalsForType, value: selectedAnimal, optionsValue: 'ID', optionsText: 'Name'"></select>

self.animalTypes = ko.observable([{"Name": "Tamed","ID": "1"},
{"Name": "Wild","ID": "2"},
{"Name": "Something else","ID": "3"}]);

self.animals = [{"Name": "Cat","ID": "1"},
{"Name": "Lion","ID": "2"},
{"Name": "Cat","ID": "1"},
{"Name": "Tiger","ID": "2"}];
self.animalType = ko.observable();
self.selectedAnimal = ko.observable();
self.animalsForType = ko.computed(function () {
var selectedType = self.animalType();
return !selectedType ? [] : self.animals.filter(function (animal) {
return animal.ID == selectedType;
});
});

希望对你有帮助!

关于javascript - 基于 ID Knockoutjs 的两个下拉选项绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22515993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com