knockoutjs表格增加更新删除

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2</title>
<script type="text/javascript" src="js/knockout-2.2.0.debug.js"></script>
<script type="text/javascript" src="js/jquery-2.1.0.js"></script>
<script type="text/javascript">
//定义user数据对象
function UserViewModel(id, name, score) {
var self = this;
self.id = ko.observable(id);
self.name = ko.observable(name);
self.score = ko.observable(score);
}
//定义ViewModel
function ViewModel() {
var self = this;
self.users = ko.observableArray(); //添加动态监视数组对象
self.removeUser = function(user) {
self.users.remove(user);
}
self.totalscore = ko.computed(function() {
var total = 0;
$.each(self.users(), function(i, u) {
total += u.score();
})
return total;
});
};
$(function() {
var vm = new ViewModel();
//预先添加一些数据
vm.users.push(new UserViewModel("d1", "rohelm", 121));
vm.users.push(new UserViewModel("d2", "halower", 125));
$("#btnAddUser").click(
function() {
vm.users.push(new UserViewModel($("#u_id").val(), $(
"#u_name").val(), parseInt($("#u_score").val())));
});
$("#btnUpdateScore").click(
function() {
vm.users()[vm.users().length - 1].score(
parseInt($("#u_score").val())).name(
$("#u_name").val()).id($("#u_id").val());
});
ko.applyBindings(vm);
});
</script>
</head>

<body>
<section style="margin: 250px">
<section>
ID <input type="text" id="u_id" style="width: 30px"> Name <input
type="text" id="u_name" style="width: 30px"> Score <input
type="text" id="u_score" style="width: 30px"> <br /> <input
value="Add" id="btnAddUser" type="button"
style="width: 200px; background-color: #ff6a00;" /> <br /><span
data-bind="text: users().length"> </span> 条--------------合计 <span
data-bind="text: totalscore"> </span></section>
<section>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Score</th>
<th>Option</th>
</tr>
</thead>
<tbody data-bind="foreach: users">
<tr>
<td><span data-bind="text: id"> </span></td>
<td><span data-bind="text: name"> </span></td>
<td><span data-bind="text: score"> </span></td>
<td><a href='#' data-bind="click: $root.removeUser">
Remove </a></td>
</tr>
</tbody>
</table>
<input value="Update测试" id="btnUpdateScore" type="button"
style="width: 200px; background-color: #ff6a00;" /> <br />
</section>
</section>
</body>

</html>

界面:修改于http://www.aizhengli.com/knockoutjs-shizhan/88/knockoutjs-shishi.html

 

转载于:https://www.cnblogs.com/jiduoduo/p/6192548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值