1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<!DOCTYPE html  >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
span{ cursor: pointer;}
</style>
<script src="jq.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var search = $('#search');
var btSearch = $('#btSearch');

var phoneBook = $('#phoneBook');
var name = $('#name');
var phone = $('#phone');
var add = $('#add');

//开始程序
var db = openDatabase('phoneBook', '', 'my', 102400);

init();

add.click(function () {
save(name.val(), phone.val());
});
btSearch.click(function () {
init(search.val())
});
$('#phoneBook span').click(function () {
deleteByName($(this).attr('name'));
s = '';
});


//初始化界面
function init(name) {
db.transaction(function (tx1) {
tx1.executeSql('create table if not exists phoneBook(name text, phone text)', []);
var sql = 'select * from phoneBook where 1=1';
var param = [];
if (name) {
sql += ' and name=? ';
param.push(name);
}
tx1.executeSql(sql, param, function (tx1, rs) {
phoneBook.html('');
for (var i = 0, len = rs.rows.length; i < len; i++) {
var data = rs.rows.item(i);
showData(data);
}
});
});
}

function showData(data) {
var str = '<div>姓名:' + data.name + ';电话:' + data.phone + ' <span onclick="del(\'' + data.name + '\')" >删除</span></div>';
phoneBook.append($(str));
}

//删除数据
function deleteByName(name) {
db.transaction(function (tx) {
tx.executeSql('delete from phoneBook where name=?', [name], function (tx, rs) {
init();
})
});
}
window.del = deleteByName;
//增加
function save(name, phone) {
db.transaction(function (tx) {
tx.executeSql('insert into phoneBook values(?, ?)', [name, phone], function (tx, rs) {
var d = {};
d.name = name;
d.phone = phone;
showData(d);
})
});
}

});

</script>
</head>
<body>
<h1>
本地数据库实现web通讯录</h1>
<input type="text" id="search" placeholder="联系人姓名" />
<button id="btSearch">
搜索</button>

<div id="phoneBook">
</div>
<hr />
姓名:<input type="text" id="name" /><br />
手机:<input type="text" id="phone" /><br />
<button id="add">
添加到通讯录</button>
</body>
</html>