<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>基础</title>
<script type="text/javascript" src="js/base.js"></script>
</head>
<body>
<div>
<label for="name">姓名:</label><input id="name" name="name" type="text" /><br/>
<label for="date">日期:</label><input id="date" name="date" type="text" /><br/>
<a href="javascript:void(0)" onclick="add()">添加</a>
<a href="javascript:void(0)" onclick="find()">查询</a>
<div id = "result"></div>
--------------------------------------
<div id="edit">
<label for="name">姓名:</label><input class="name" name="name" type="text" /><br/>
<label for="date">日期:</label><input class="date" name="date" type="text" /><br/>
<label onclick="save()">保存</label>
</div>
</div>
<script>
var tickets = []; // [{"id":"1","name":"餐饮","date":"20181108"},{"id":"2","name":"火车票","date":"20181109"}]
//增加
function add(){
var name = document.getElementById("name").value;
var date = document.getElementsByName("date")[0].value;
var obj = {};
obj.id = tickets.length + 1;
obj.name = name;
obj.date = date;
console.log(JSON.stringify(obj));
tickets.push(obj);
console.log(tickets.length);
}
//查询
function find(){
var html = "";
for(var i = 0; i < tickets.length;i++){
html += "<p><label>"+tickets[i].id+"</label>|<label>" + tickets[i].name+ "</label>|<label>"+tickets[i].date+"</label> <label onclick='del(""+tickets[i].id+"")'>删除</label><label onclick='edit(""+tickets[i].id+"")'>修改</label></p>";
}
document.getElementById("result").innerHTML = html;
}
//修改
function edit(id){
var obj = null;
tickets.forEach(function(e){
if(e.id == id){
obj = e;
}
})
console.log(JSON.stringify(obj));
document.getElementsByClassName("name")[0].value = obj.name;
document.getElementsByClassName("date")[0].value = obj.date;
document.getElementById("edit").setAttribute("data-id",obj.id);
}
//保存
function save(){
// 待保存的id
var id = document.getElementById("edit").getAttribute("data-id");
var name = document.getElementsByClassName("name")[0].value;
var date = document.getElementsByClassName("date")[0].value;
tickets.forEach(function(e){
if(e.id == id){
e.name = name;
e.date = date;
}
})
}
//删除
function del(id){
console.log("id是" + id);
for(var i = 0; i < tickets.length;i++){
if(tickets[i].id == id){
tickets.splice(i,1);
}
}
}
</script>
</body>
</html>