https://www.cnblogs.com/zhangzuwei/p/16574791.html
注意
1.删除表,创建表只能在数据库版本升级里面进行。
2.keypath: key 要和表字段对应,而且格式要一样,不然不运行不报错。
3.使用 autoIncrement: true 代替 keypath: key, 则不需要写关键字段。
<html>
<head>
<title>IndexedDB</title>
<style>
h1 { text-align:center; }
table { margin:auto; border-collapse:collapse; }
th, td { text-align:center; padding:10px; border:1px solid black; }
</style>
</head>
<body>
<h1>Contact</h1>
<p id="msg"></p>
<table id="table"></table>
<script>
if (!window.indexedDB) {
msg.innerText = "Your browser doesn't support IndexedDB.";
} else {
const customerData = [
{ name: "Bill", age: 35, email: "bill@company.com" },
{ name: "Donna", age: 32, email: "donna@home.org" },
{ name: "Jenny", age: 23, email: "jenny@msn.com" },
{ name: "Henry", age: 43, email: "Henry@outlook.com" },
{ name: "Kaili", age: 53, email: "Kaili@outlook.com" }
];
var db;
var request = window.indexedDB.open("MyTestDatabase", 13);
request.onerror = function(event) {
console.log(event);
msg.innerText = event.target.error;
};
request.onupgradeneeded = function(event){
db = event.target.result;
db.deleteObjectStore("customers");
var objectStore = db.createObjectStore("customers", { autoIncrement: true });
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
objectStore.transaction.oncomplete = function(event){
var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
customerData.forEach(function(customer){
customerObjectStore.add(customer);
});
};
};
request.onsuccess = function(event){
var i = 1;
var tr = document.createElement('tr');
var th = document.createElement('th');
th.textContent = 'id';
tr.append(th);
th = document.createElement('th');
th.textContent = 'name';
tr.append(th);
th = document.createElement('th');
th.textContent = 'age';
tr.append(th);
th = document.createElement('th');
th.textContent = 'email';
tr.append(th);
table.append(tr);
db = event.target.result;
var objectStore = db.transaction("customers").objectStore("customers");
objectStore.openCursor().onsuccess = function(event){
var cursor = event.target.result;
if (cursor) {
tr = document.createElement('tr');
var td = document.createElement('td');
td.textContent = i;
tr.append(td);
td = document.createElement('td');
td.textContent = cursor.value.name;
tr.append(td);
td = document.createElement('td');
td.textContent = cursor.value.age;
tr.append(td);
td = document.createElement('td');
td.textContent = cursor.value.email;
tr.append(td);
table.append(tr);
cursor.continue();
i++;
} else {
console.log("No more cursor!");
}
};
};
}
</script>
</body>
</html>