gpt4 book ai didi

jquery - knockout 三个级联下拉菜单

转载 作者:行者123 更新时间:2023-12-01 07:06:45 25 4
gpt4 key购买 nike

我真的很喜欢 cartEditor 中的实例。这就是我需要的。好吧,如果我想添加另一个下拉菜单,几乎会怎么样。例如,如果我想向现有示例添加另一个字段country。场景如下:我选择国家/地区、车辆类别,然后根据此选择车辆本身。如何将两个下拉菜单绑定(bind)到第三个下拉菜单?

数据库中有关此类的表:

table 车

id名称国家ID类别ID

表格类别

ID名称

表国家

ID名称

实际示例的文件位于 knockoutjs.com

最佳答案

您将继续遵循相同的原则:

  • 在数组或普通对象中定义数据
  • 构建使数据可渲染和可选择的 View 模型
  • 创建 ko.pureCompulated 属性,根据用户输入选择数据子集。

例如,假设您的产品同时具有类别国家/地区:

var products = [
{
name: "Cheese",
country: "The Netherlands",
category: "Dairy"
}
]

现在,如果您有两个可观察对象,绑定(bind)到您的 UI:

this.selectedCountry = ko.observable();
this.selectedCategory = ko.observable();

您可以创建一个ko.pureCompulated来选择满足要求的产品:

this.selectedProducts = ko.pureComputed(function() {
return products.filter(function(product) {
return product.category === this.selectedCategory() &&
product.country === this.selectedCountry();
});
}, this);

示例:

var products = [
{
name: "Gouda Cheese",
country: "The Netherlands",
category: "Dairy"
},
{
name: "Camambert",
country: "France",
category: "Dairy"
},
{
name: "Red Wine",
country: "France",
category: "Alcoholic beverages"
}

];

var ViewModel = function() {
// These will be bound to your dropdowns' selections
this.selectedCountry = ko.observable();
this.selectedCategory = ko.observable();

// This computed calculates which products from your data
// meet the requirements whenever one of the selections changes
this.selectedProducts = ko.pureComputed(function() {
return products.filter(function(product) {
return product.category === this.selectedCategory() &&
product.country === this.selectedCountry();
}.bind(this));
}, this);

// Here, we create a list of countries that appear in your data,
// this list is used to fill the dropdown's options
this.countries = getKeyUniques(products, "country");

// Do the same for categories
this.categories = getKeyUniques(products, "category");

};

ko.applyBindings(new ViewModel());

// Utils
function getKeyUniques(arr, key) {
return Object.keys(arr.reduce(function(map, item) {
map[item[key]] = true;
return map
}, {}));
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<select data-bind="options: countries, value: selectedCountry"></select>
<select data-bind="options: categories, value: selectedCategory"></select>

<ul data-bind="foreach: selectedProducts">
<li data-bind="text: name"></li>
</ul>

关于jquery - knockout 三个级联下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40804514/

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