use*_*436 3 javascript knockout.js
我正在尝试使用具有值的选项激活两个选择字段,例如。<option value='...'>...</option>使用 Knockoutjs。
并根据第一个选择字段中的选定值填充第二个选择字段选项。
仅供参考,我找到了http://knockoutjs.com/examples/cartEditor.html,但这也没有使用 optionsValue 所以它没有帮助。
这是我的观点:
<select data-bind="options: list,
optionsCaption: 'Select...',
optionsText: 'location',
optionsValue: 'code',
value: selectedRegion">
</select>
<!-- ko with : selectedRegion -->
<select data-bind="options: countries,
optionsCaption: 'Select...',
optionsText: 'location',
optionsValue: 'code',
value: $parent.selectedCountry">
</select>
<!-- /ko -->
Run Code Online (Sandbox Code Playgroud)
这是我的观点:
var packageData = [
{
code : "EU",
location: 'Euprope',
countries : [
{ location: "England", code: 'EN' },
{ location: "France", code: 'FR' }
]
},
{
code : "AS",
location: 'Asia',
countries : [
{ location: "Korea", code: 'KO' },
{ location: "Japan", code: 'JP' },
]
}
];
function viewModel(list, addons) {
this.list = list;
this.selectedRegion = ko.observable();
this.selectedCountry = ko.observable();
}
ko.applyBindings(new viewModel(packageData));
Run Code Online (Sandbox Code Playgroud)
如果在上面运行,我会收到以下 JS 错误。
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: options: countries,
optionsCaption: 'Select...',
optionsText: 'location',
optionsValue: 'code',
value: $parent.selectedCountry
Message: countries is not defined
Run Code Online (Sandbox Code Playgroud)
如果我在我的视图中丢失 'optionsValue: 'code,' 行(一个用于第一个选择字段,另一个用于第二个选择字段。但是这不会填充选项值,这不是我想要的。
例如,<option value>...</option>代替<option value="[country code]">...</option>.
有人可以帮助我如何修复我的代码以便我得到<option value="[country code]">...<option>吗?
非常感谢。
问题是,当您设置optionsValue属性时selectedRegion,现在只填充了代码。代码属性下面没有国家属性,因此绑定失败。解决此问题的一种方法是使用计算的 observable 返回基于selectedRegion代码的国家/地区。
self.countryList = ko.computed(function () {
var region = self.selectedRegion();
var filtered = ko.utils.arrayFirst(self.list, function (item) {
return item.code == region;
});
if (!filtered) {
return []
} else {
return filtered.countries;
}
});
Run Code Online (Sandbox Code Playgroud)
然后您只需更改绑定以使用计算:options: $root.countryList。
工作示例:http : //jsfiddle.net/infiniteloops/AF2ct/