gpt4 book ai didi

javascript - Knockout - 将用户输入添加到表中时出现问题

转载 作者:行者123 更新时间:2023-11-28 20:09:20 25 4
gpt4 key购买 nike

这是我的 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 绑定(bind)

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
});

}
}

问题是,虽然通过 form 将新行添加到表中,但是当添加新行时,前一行会被它覆盖。我该如何克服它?

最佳答案

在您的代码中,当您添加新项目时,您推送的可观察对象而不是它的值。因此,当您继续添加与之前推送的可观察对象相关联的新项目时,旧值将被覆盖。

因此,更改您的 showMe 函数以推送您的 observable 对象的值:

self.showMe = function() {
self.awards.push({
name: self.newName(),
phone: self.phone(),
email: self.email(),
address: self.adrs()
});

}

JsFiddle Demo

关于javascript - Knockout - 将用户输入添加到表中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20175063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com