【发布时间】:2012-07-21 23:42:53
【问题描述】:
有一个奇怪的问题,在我指定 optionsValue 之前一切正常。你可以在这里看到我的问题
有效 http://jsfiddle.net/abritez/ttyhE/2/
不起作用 http://jsfiddle.net/abritez/ttyhE/4/
您需要做的就是尝试使用已注释的 select 运行它,然后您会在尝试级联时看到问题。
JSON 数据
var productCategories = [{
"name": "Comapany A",
"abbr": "cA",
"disiplineList": [{
"name": "Math",
"abbr": "math",
"courseList": [{
"name": "Algebra",
"abbr": "alg"
}]
}, {
"name": "English",
"abbr": "eng",
"courseList": [{
"name": "Phonics",
"abbr": "phon"
}]
}]
}, {
"name": "Company B",
"abbr": "cB",
"disiplineList": [{
"name": "Gym",
"abbr": "gym",
"courseList": [{
"name": "Kick Ball",
"abbr": "kb"
}]
}]
}];
HTML 代码
<table width='100%'>
<tbody data-bind='foreach: lines'>
<tr>
<td>
<select data-bind='options: productCategories, optionsText: "name", optionsCaption: "Select...", value: company'> </select>
</td>
</tr>
<tr>
<td data-bind="with: company">
<select data-bind='options: disiplineList, optionsText: "name", optionsCaption: "Select...", value: disipline'> </select>
</td>
</tr>
<tr>
<td data-bind="with: disipline">
<select data-bind='options: courseList, optionsText: "name", value: product'></select>
</td>
</tr>
</tbody>
</table>
Java 脚本 (knockoutjs)
function ProductLine(){
self.company = ko.observable();
self.disipline = ko.observable();
self.product = ko.observable();
// Whenever the category changes, reset the product selection
self.company.subscribe(function() {
self.disipline(undefined);
self.product(undefined);
});
}
function Product(){
self.lines = ko.observableArray([new ProductLine()]); // Put one line in by default
}
ko.applyBindings(new Product());
【问题讨论】:
-
不要使用 optionsValue 他们的使用很尴尬而且不是很有价值..你不需要它。告诉我们你真正的问题是什么。 optionsValue 仅适用于数字,并且当您使用 observableArray 构建 select 时。像这样:link
-
我要做的就是让值成为文本的缩写。例如,“United States of America”的值为“usa”,“New York City”的值为“nyc”。
标签: knockout.js