将数据存储在 IndexedDB 中

Hel*_*RlD 3 javascript indexeddb

您好,我正在尝试将三个字段存储在 IndexedDB 中。它在浏览器中显示了每三个索引的名称.. content、content2 和 content3。但是,数据仅保存到 content3 中?

这是我的源代码:

<script type="text/javascript">
          var request = indexedDB.open("synker");
          var db;
          request.onupgradeneeded = function() {
          // The database did not previously exist, so create object stores and indexes.
          db = request.result;
          var store = db.createObjectStore("notes", {keyPath: "ID"});
          store.createIndex("content","content", { unique: false });
          store.createIndex("content2","content2", { unique: false });
          store.createIndex("content3","content3", { unique: false });
        };

        request.onsuccess = function() {
          db = request.result;
        };

        function addData(data)  {
            var tx = db.transaction("notes", "readwrite");
            var store = tx.objectStore("notes");
            store.put({content: data, ID:1});
            store.put({content2: data, ID:1});
            store.put({content3: data, ID:1});
        }
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 5

每次调用 store.put 都会存储一个单独的对象。对象是属性的集合。索引是一种根据多个对象的属性进行操作的数据结构。

您可能希望仅使用一次 store.put 调用来存储具有多个属性的单个对象。

function addData(data) {
  var tx = ...;
  var store = ...;

  // One call to put that stores all three properties together in one object.
  store.put({'content': data, 'content2': data, 'content3': data});
}
Run Code Online (Sandbox Code Playgroud)