这是我的HTML代码
<tbody data-bind="foreach: awards">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: email"></td>
<td data-bind="text: phone"></td>
<td data-bind="text: address"></td>
<td ><input type="button" class="btn btn-success pull-centre" value="Update!" /></td>
<td ><input type="button" class="btn btn-success pull-centre" value="Delete!" /></td>
</tr>
</tbody>
<form class="well form-inline" id="myform" >
<div class="form-group">
<label><b>Form</b></label>
</div>
<div class="form-group">
<input type="text" data-bind="value:newName" class="span4" placeholder="Name" id="n" >
</div>
<br>
<div class="form-group">
<input type="text" data-bind="value:phone" class="span4" placeholder="Phone Number" id="p">
</div>
<br>
<div class="form-group">
<input type="text" class="span4" data-bind="value:email" placeholder="Email" id="e">
</div>
<br>
<div class="form-group">
<input type="text" class="span4" placeholder="Address" data-bind="value:adrs" id="a">
</div>
<br>
<button type="button" class="btn" data-bind="click: showMe">Find</button>
</div>
</form>
这是javascript + ko绑定
function komodel() {
var self = this;
self.newName = ko.observable();
self.phone = ko.observable();
self.email = ko.observable();
self.adrs = ko.observable();
self.awards = ko.observableArray([{
name: "sohaib",
phone: "03009496301",
email: "has@yahoo.com",
address: "faisal town"
}, {
name: "pappu",
phone: "45609496301",
email: "asdhas@yahoo.com",
address: "asdasd jinga lala faisal town"
}]);
self.showMe = function() {
self.awards.push({
name: self.newName,
phone: self.phone,
email: self.email,
address: self.adrs
});
}
}
问题在于尽管通过表格将新行添加到表中,但是当添加新行时,前一个行会被它覆盖。我该如何克服它?
答案 0 :(得分:3)
在你的代码中添加新项目时,推送observable
对象而不是它的值。因此,当您继续添加与先前推送的observable
个对象关联的新项目时,旧值将被覆盖。
因此,将showMe
函数更改为推送observable
个对象的值:
self.showMe = function() {
self.awards.push({
name: self.newName(),
phone: self.phone(),
email: self.email(),
address: self.adrs()
});
}
的 JsFiddle Demo 强> 的