TAG
CSS
JavaScript
Result
Run
License
<table id="list" class="list"> <caption>Membsrs</caption> <thead> <tr> <th>Email(PK)</th> <th>Name</th> <th>Age</th> <th></th> </tr> </thead> </table>
.list { border-collapse: collapse; } .list > caption { text-align: left; font-weight: bold; } .list > thead { background-color: darkgray; } .list tr { border: 1px solid gray; border-style: solid none solid none; } .list th, .list td { padding: 3px 10px; } .list th:not(:last-child) { border-right: 1px white solid; }
window.addEventListener("load", () => { const $members = [ { email: "john@demo.com", name: "John", age: 20 }, { email: "merry@demo.com", name: "Merry", age: 21 }, { email: "tom@demo.com", name: "Tom", age: 19 } ]; const $dbName = "example3"; const $dbVersion = 1; const $objectStoreName = "members"; let db, transaction; const $idbOpenDbReq = window.indexedDB.open($dbName, $dbVersion); const $elList = document.getElementById("list"); $idbOpenDbReq.onsuccess = function() { db = this.result; [...db.objectStoreNames].forEach(name => console.log(`Object Store: ${name}`)); insert(); display(); }; $idbOpenDbReq.onupgradeneeded = function(e) { db = this.result; if(e.oldVersion < $dbVersion) { [...db.objectStoreNames].forEach((objectStore, index) => { if(objectStore.indexOf("members") > -1) { db.deleteObjectStore(objectStore); console.log(`delete to ${objectStore}`); } }); } let objectStore = db.createObjectStore($objectStoreName, { keyPath: "email" }); objectStore.createIndex("age", "age"); }; function insert() { transaction = db.transaction($objectStoreName, "readwrite"); const $objectStore = transaction.objectStore($objectStoreName); $members.forEach(record => $objectStore.add(record)); } function display() { transaction = db.transaction($objectStoreName, "readonly"); let objectStore = transaction.objectStore($objectStoreName); let idbCursorWithValue = objectStore.openCursor(); initList(); idbCursorWithValue.onsuccess = makeList; } function initList() { if(!$elList.tBodies.length) { $elList.createTBody(); } else { let elTBody = $elList.tBodies.item(0); [...elTBody.children].forEach(el => el.remove()); } } function makeList(e) { let cursor = e.target.result; let elTBody = $elList.tBodies.item(0); if(cursor) { let elTr = elTBody.insertRow(); let elCell = elTr.insertCell(); elCell.textContent = cursor.value.email; elCell = elTr.insertCell(); elCell.textContent = cursor.value.name; elCell = elTr.insertCell(); elCell.textContent = cursor.value.age; cursor.continue(); } } });
Console
expand_less
License
License
by DevDic
Close