3
我對knockoutjs相當陌生。我正在創建一個簡單的表格,並嘗試總結「總計」列中的所有值。另外,我還使用knockoutjs實現了「添加列」和「刪除列」功能。使用knockoutjs獲取行的總數和添加和刪除行
問題是,添加和刪除功能並且不起作用。此外,「TotalSurcharge」值不顯示在用戶界面上。
這裏是我的JS:
// Class to represent a row in the table
function addMaterial() {
this.name = ko.observable("");
this.quantity = ko.observable("");
this.rate = ko.observable(0);
this.formattedTotal = ko.computed(function() {
return this.rate() * this.quantity();
}, this);
}
function documentViewModel(){
var self = this;
//create a mateirals array
self.materials = ko.observableArray([
new addMaterial()
]);
// Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.materials().length; i++)
total += self.materials()[i].formattedTotal();
return total;
});
// Operations
self.addMaterial = function() {
self.materials.push(new addMaterial());
}
self.removeMaterial = function(material) { self.materials.remove(material) }
}
ko.applyBindings(new documentViewModel());
這裏是我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src='knockout-2.2.0.js'></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Quantity </th>
<th>Rate</th>
<th>Total</th>
</tr>
</thead>
<tbody "foreach: materials">
<tr class="info">
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: quantity" /></td>
<td><input data-bind="value: rate" /></td>
<td data-bind="text: formattedTotal"></td>
<td><a href="#" data-bind="click: $root.removeMaterial">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addMaterial, enable: materials().length < 5">Add Row</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
</div>
</body>
<script type='text/javascript' src='application.js'></script>
</html>
我檢查了控制檯上的錯誤的瀏覽器,但我沒有得到任何錯誤。任何想法我做錯了什麼?
您忘記了材料數組初始化中的'new'。此外,您的總費用計算沒有任何意義。你不應該把每個'formattedTotal'項目加到你的總和上嗎? 'self'沒有'formattedTotal'。 – CrimsonChris
@CrimsonChris,我得到了添加和刪除現在工作。感謝您的建議。據我所知,我修改了總排放計算函數,但仍然無法正常工作。有任何想法嗎 ? – bangbang
我的不好,在formattedTotal後忘了括號。修復。謝謝 – bangbang