html:
<table>
<caption>添加用户</caption>
<tr>
<td>姓名</td>
<td><input type="text" id="username"></td>
</tr>
<tr>
<td>性别</td>
<td><input type="text" id="sex"></td>
</tr>
<tr>
<td>年龄</td>
<td><inout type="text" id="age"></td>
</tr>
<tr>
<td>所在地</td>
<td><input type="text" id="place"></td>
</tr>
<tr>
<td>
<button onclick="addUser()">添加</button>
</td>
</tr>
</table>
<div id="con"></div>
js:
// 第三步创建几个对象
function Person(name,sex,age,placee){
this.name = name;
this.sex= sex;
this.age = age;
this.placee = placee;
}
//第四步 增加,prototype 属性使您有能力向对象添加属性和方法。
Person.prototype.add=function(){
var user ={};
user.name =this.name;
user.sex =this.sex;
user.age =this.age;
user.placee =this.placee;
users.push(user);
user={};//下次加的时候为空
}
// 第六步做修改
Person.prototype.up=function(i){
var user=users[i];
user.name=this.name;
user.sex=this.sex;
user.age=this.age;
user.placee=this.placee;
}
// 第五步增加
function addUser(){
var username = document.getElementById("username").value;
var sex = document.getElementById("sex").value;
var age = document.getElementById("age").value;
var placee = document.getElementById("placee").value;
var p1=new Person(username,sex,age,placee);
p1.add();
bindUser();
}
// 第7步删除
function delUser(i){
if(confirm("确定删除吗?")){
users.splice(i,1);
bindUser();
}
}
// 第七步更新
function upUser(i){
var username = document.getElementsByClassName("name"+i)[0].innerHTML;
var sex = document.getElementsByClassName("sex"+i)[0].innerHTML;
var age = document.getElementsByClassName("age"+i)[0].innerHTML;
var placee = document.getElementsByClassName("placee"+i)[0].innerHTML;
var p1 = new Person(username,sex,age,placee);
p1.up(i);
bindUser();
alert("更新成功");
}
// 第一步写数组
var users = [
{name: "hh",sex:"女",age:23,placee:"广州"},
{name: "ff",sex:"男",age:27,placee:"江西"},
{name: "花花",sex:"女",age:23,placee:"广州"},
{name: "锋",sex:"男",age:27,placee:"广州"},
{name: "hh",sex:"女",age:28,placee:"广州"},
{name: "hh",sex:"女",age:28,placee:"广州"},
];
// 第二步写入页面
window.onload=function(){
bindUser();
}
function bindUser(){
var str="<table>";
str+="<tr><th>编号</th><th>姓名</th><th>性别</th><th>年龄</th><th>所在地</th><th>删除</th><th>更新</th><tr>";
for(var i=0;i<users.length;i++){
str+="<tr>";
str+="<td>"+(i+1)+"</td>;
str+="<td contenteditable='true' class='name"+i+"'>"+users[i].name+"</td>;
str+="<td contenteditable='true' class='sex"+i+"'>"+users[i].sex+"</td>";
str+="<td contenteditable='true' class='age"+i+"'>"+users[i].age+"</td>";
str+="<td contenteditable='true' class='placee"+i+"'>"+users[i].placee+"</td>";
str+="<td><button onclick='delUser("+i+")'>删除</button></td>";
str+="<td><button onclick='upUser("+i+")'>更新</button></td>";
}
str +="</table>";
document.getElementById("con").innerHTML = str;
}