【发布时间】:2015-06-02 14:27:09
【问题描述】:
我正在学习 knockout.js。因此,我尝试构建一个示例购物车,最初下拉菜单将带有产品数据。当用户选择任何产品时,相应的价格和数量将在右侧输入控件中填写,并由计算属性自动计算小计。
最初,当我运行我的程序时,会显示购物车的一个数据,但是当我选择任何产品时,价格和数量值不会被填满,也不会显示小计。我是 KO 的新手,这就是为什么我犯了一些在我眼前并不清楚的愚蠢错误。所以请指导我在哪里犯了错误。
这是我的完整代码
<table id="table1" cellspacing="0" cellpadding="0" border="0">
<tr>
<th style="width:150px">Product</th>
<th>Price ($)</th>
<th>Quantity</th>
<th>Amount ($)</th>
</tr>
<tbody data-bind='template: {name: "orderTemplate", foreach: lines}'></tbody>
</table>
<script type="text/html" id="orderTemplate">
<tr>
<td><select data-bind="options: products,
optionsText: 'name',
value: id,
optionsCaption:'--Select--'">,
value: $parent.product
</select>
</td>
<td><span data-bind="value: price" /></td>
<td><input data-bind="value: quantity" /></td>
<td><span data-bind="value: subtotal" /></td>
</tr>
</script>
<script type="text/javascript">
var _products = [
{
"name": "1948 Porsche 356-A Roadster",
"price": 53.9
, quantity: 1
},
{
"name": "1948 Porsche Type 356 Roadster",
"price": 62.16
, quantity: 1
},
{
"name": "1949 Jaguar XK 120",
"price": 47.25
, quantity: 1
},
{
"name": "1952 Alpine Renault 1300",
"price": 98.58
, quantity: 1
},
{
"name": "1952 Citroen-15CV",
"price": 72.82
, quantity: 1
},
{
"name": "1956 Porsche 356A Coupe",
"price": 98.3
, quantity: 1
},
{
"name": "1957 Corvette Convertible",
"price": 69.93
, quantity: 1
}];
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
var CartLine = function () {
var self = this;
self.products = ko.observableArray(_products);
self.product = ko.observable();
self.quantity = ko.observable(1);
self.price = ko.observable(1);
self.subtotal = ko.computed(function () {
return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
});
};
var Cart = function () {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
};
ko.applyBindings(new Cart());
</script>
【问题讨论】:
-
您没有关闭
data-bind元素中的data-bind属性。此外,在您的<span>元素中,您需要使用text:而不是value:绑定。
标签: jquery knockout.js