[英]Knockout JS: Dynamically adding and removing table row
我在這里使用淘汰賽js。
我有一個HTML表,該表有4列。 我有向表中添加一行的按鈕,然后針對每行刪除按鈕以將其刪除。 HTML表格如下。
<table class="table table-bordered">
<thead class="mbhead">
<tr class="mbrow">
<th>Input</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td>
<select class="form-control common-input-text" data-bind="event: { change: $root.addNewItem }">
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
</select>
</td>
<td><span class="input-small" data-bind="value: firstName" /></td>
<td><span class="input-small" data-bind="value: lastName" /></td>
<td><span class="input-small" data-bind="value: address" /></td>
<td>
<input type="button" value="Remove Row" data-bind="click: removeRow" class="btn btn-danger" />
</td>
</tr>
</tbody>
</table>
<input type="button" value="Add Row" class="btn btn-primary" data-bind="click: addRow" />
我的淘汰賽是:
(function () {
var ViewModel = function () {
var self = this;
//Empty Row
self.items = ko.observableArray([]);
self.addRow = function () {
self.items.push(new Item());
};
self.removeRow = function (data) {
self.items.remove(data);
};
}
var Item = function (fname, lname, address) {
var self = this;
self.firstName = ko.observable(fname);
self.lastName = ko.observable(lname);
self.address = ko.observable(address);
};
vm = new ViewModel()
ko.applyBindings(vm);
})();
當我單擊添加行時,它會添加第一行,但會給我控制台錯誤:
tickout.js:73未捕獲的ReferenceError:無法處理綁定“單擊:> function(){返回removeRow}”消息:未定義removeRow
當我再次單擊添加行時,它給了我另一個控制台錯誤:
未捕獲的錯誤:您不能多次將綁定應用於同一元素。
當我單擊removeRow時,沒有任何反應。
當我注釋掉removeRow的代碼時,我可以添加一個新行。 不知道我要去哪里錯了。
這是我的jsfiddle:
https://jsfiddle.net/aman1981/nz2dtud6/2/
在使用數據綁定foreach
,上下文會更改為其子元素的上下文。 要訪問父級上下文,您需要添加$parent
來訪問removeRow
<td>
<input type="button" value="Remove Row" data-bind="click: $parent.removeRow" class="btn btn-danger" />
</td>
由於您的<tbody>
通過使用foreach: items
綁定定義了一個新范圍 ,因此您需要使用$parent.removeRow
來引用該方法。
<input data-bind="click: $parent.removeRow" type="button" value="Remove Row" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.