我有两个下拉菜单,一个依赖于另一个(级联)。 “MainCategories”上的选择决定了“SubCategories”的项目。 此外,“MainCategories”上的选择也决定了表行的可见性。 以下是我尝试过的:
<table>
<tbody data-bind="foreach: contacts">
<tr>
<td>MainCategories:
<select data-bind='options: MyCategories, value: mycategory, optionsText: "Type", optionsValue: "Type",optionsCaption: "Select..."'></select>
</td>
<td>
<!-- ko with: mycategory -->SubCategories:
<select data-bind='options: Categories, optionsText: "Category", optionsCaption: "Select...", value: $parent.product'></select>
<!-- /ko -->
</td>
</tr>
<tr data-bind="visible:mycategory()=='Type1'">
<td>I am visible</td>
</tr>
</tbody>
</table>
<script type = "text/javascript" >
var MyCategories = [{
"Categories": [{
"Category": "Category1"
}, {
"Category": "Category2"
}],
"Type": "Type1"
}, {
"Categories": [{
"Category": "Category3"
}, {
"Category": "Category4"
}],
"Type": "Type2"
}];
var initialData = [{
category: "Mobile",
product: "Nokia"
}];
var ContactsModel = function (contacts) {
var self = this;
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
return {
mycategory: ko.observable(contact.category),
product: ko.observable(contact.product)
};
}));
};
ko.applyBindings(new ContactsModel(initialData));
</script>
如果我删除optionsValue: "Type",那么“SubCategories”就会获得正确的项目。但表行的可见性未按预期工作。 如果我有 optionsValue: "Type",则不会填充“SubCategories”。而且,当我更改“MainCategories”的选项 1 或 2 次时,只有可见性工作正常。
请帮我找出我在这里做错了什么。 谢谢,
最佳答案
我读了你的问题,我有一种感觉,如果没有足够解决它,你可以应用它,这会回答它 -
*问题* -
您需要使用 Knockout 有一个级联下拉列表来选择一个值并将您的可观察值设置为等于子选择的选定对象。
*解决方案* -
使用计算使第二个下拉列表依赖于第一个下拉列表。示例 -
var selectedParent = ko.observable();
var parentCategories = ko.observableArray(MyCategories);
var childCategories = ko.computed(function () {
if (!selectedParent()) { return new Array(); }
var childArray = [];
// get the values you want for the child here
return childArray;
});
通过添加 if (!selectedParent()),您可以使 childCategories 依赖于 selectedParent。每当选择更改时,子类别都会自动更新。
那么你的 View 可以是这样的 -
<td>MainCategories:
<select data-bind='options: parentCategories, value: selectedParent, optionsText: "Type", optionsValue: "Type",optionsCaption: "Select..."'></select>
</td>
<td> SubCategories:
<select data-bind='options: childCategories, optionsText: "Category", optionsCaption: "Select...", value: $parent.product'></select>
<!-- /ko -->
</td>
关于knockout.js - knockout 级联下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17993486/