【练习】利用indexedDB实现网页数据本地存储

const list = document.querySelector('ul');
const titleInput = document.querySelector('#title');
const bodyInput = document.querySelector('#body');
const form = document.querySelector('form');
const submitBtn = document.querySelector('form button');
let bd;

function addData(e){
  e.preventDefault();

  let newItem = {title: titleInput.value, body: bodyInput.value};
  let transaction = db.transaction(['notes'], 'readwrite');
  let objectStore = transaction.objectStore('notes');
  let request = objectStore.add(newItem);
  request.onsuccess = function(){
    titleInput.value = '';
    bodyInput.value ='';
  };
  transaction.oncomplete = function(){
    console.log('Transaction completed: database modification finished.');
    displayData();
  };
  transaction.onerror = function(){
    console.log('Transaction not opened due to error');
  };
}

function displayData(){
  while(list.firstChild){
    list.removeChild(list.firstChild);
  }
  let objectStore = db.transaction('notes').objectStore('notes');
  objectStore.openCursor().onsuccess = function(e){
    let cursor = e.target.result;
    if(cursor){
      let listItem = document.createElement('li');
      let h3 =document.createElement('h3');
      let para = document.createElement('p');

      listItem.appendChild(h3);
      listItem.appendChild(para);
      list.appendChild(listItem);

      h3.textContent = cursor.value.title;
      para.textContent = cursor.value.body;
      listItem.setAttribute('data-note-id', cursor.value.id);

      let deleteBtn = document.createElement('button');
      listItem.appendChild(deleteBtn);
      deleteBtn.textContent = 'Delete';
      deleteBtn.onclick = deleteItem; 

      cursor.continue();
    } else {
      if(!list.firstChild){
        let listItem = document.createElement('li');
        listItem.textContent = 'No notes stored.';
        list.appendChild(listItem);
      }
    }
  }
}

function deleteItem(e){
  let noteId = Number(e.target.parentNode.getAttribute('data-note-id'));
  let transaction = db.transaction(['notes'], 'readwrite');
  let objectStore = transaction.objectStore('notes');
  let request = objectStore.delete(noteId);

  transaction.oncomplete = function(){
    e.target.parentNode.parentNode.removeChild(e.target.parentNode);
    console.log('Note '+noteId+' deleted.');
    if(!list.firstChild){
      let listItem = document.createElement('li');
      listItem.textContent = 'No notes stored.';
      list.appendChild(listItem);
    }
  }
}

window.onload = function(){
  let request = window.indexedDB.open('notes', 1);
  request.onerror = function(){
    console.log('Database failed to open');
  };
  request.onsuccess = function(){
    console.log('Database opened successfully');
    db = request.result;
    displayData();
  };
  request.onupgradeneeded = function(e){
    let db = e.target.result;
    let objectStore = db.createObjectStore('notes', {keyPath: 'id', autoIncrement:true});
    objectStore.createIndex('title', 'title', {unique: false});
    objectStore.createIndex('body', 'body', {unique: false});
    console.log('Database setup complete');
  };

  form.onsubmit = addData;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexedDB demo</title>
    <style>
      html {
        font-family: sans-serif;
      }

      body {
        margin: 0 auto;
        max-width: 800px;
      }

      header, footer {
        background-color: green;
        color: white;
        line-height: 100px;
        padding: 0 20px;
      }

      .new-note, .note-display {
        padding: 20px;
      }

      .new-note {
        background: #ddd;
      }

      h1 {
        margin: 0;
      }

      ul {
        list-style-type: none;
      }

      div {
        margin-bottom: 10px;
      }
    </style>
    <script src="js/index.js" defer></script>
  </head>
  <body>
    <header>
      <h1>IndexedDB notes demo</h1>
    </header>

    <main>
      <section class="note-display">
        <h2>Notes</h2>
        <ul>

        </ul>
      </section>
      <section class="new-note">
        <h2>Enter a new note</h2>
        <form>
          <div>
            <label for="title">Note title</label>
            <input id="title" type="text" required>
          </div>
          <div>
            <label for="body">Note text</label>
            <input id="body" type="text" required>
          </div>
          <div>
            <button>Create new note</button>
          </div>
        </form>
      </section>
    </main>

    <footer>
      <p>Copyright nobody. Use the code as you like.</p>
    </footer>
  </body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值