声明 js 变量/对象时出错(未捕获 DOMException)

问题描述 投票:0回答:1

我的脚本遇到错误:

未捕获的 DOMException:尝试使用不可用或不再可用的对象

脚本应检查数据库是否已满。如果没有,则用初始值填充数据库。之后显示输入字段中的值。 错误发生在

var data = marmaInfo.result

var indexedDB = window.indexedDB
var db;
    // Open (or create) the database
    var open = indexedDB.open("marmaDB", 1);
    console.log("open Db ...");

    // Create the schema
    console.log("creating schema ...");
    open.onupgradeneeded = function() {
        db = open.result;
        var store = db.createObjectStore("marmasStore", {keyPath: "id"});
    store.createIndex('sanskrit', 'sanskrit', { unique: false });
      };

    function getObjectStore(store_name, mode) {
        var tx = db.transaction(store_name, mode);
        return tx.objectStore(store_name);
    }

    open.onsuccess = function() {
        console.log("open DB DONE");
        // Start a new transaction
        db = open.result;
        store = getObjectStore("marmasStore", 'readwrite');
        //var tx = db.transaction("marmasStore", "readwrite");
        //var store = tx.objectStore("marmasStore");
        //var index = store.index("NameIndex");

        // Initial data
        const initialMarmaData = [
            { id: "ani_ll", sanskrit: "ani"},
        ];

        // Store values
        // initial DB filling 
        
        var key = $('#marmaID').val();
        console.log("key " + key );
        var marmaInfo = store.get(key);
        //marmaInfo.onsuccess = function(evt) {
        var data = marmaInfo.result
        if (data.sanskrit == 0){
            console.log("record " + key + ":", record);
            console.log("initial filling DB ...");
            var store = getObjectStore("marmasStore", 'readwrite');
            initialMarmaData.forEach((marma) => {
                var request = store.put(marma);
                request.onsuccess = (event) => {
                    console.log(event.target.result + " initial filling DB DONE");
                };
            });
        }
        //}
        //fill the form with DB values
        console.log("filling form ...");
        document.getElementById('sanskrit').value = data.sanskrit;
        console.log("filling form DONE");
        
      }
javascript indexeddb
1个回答
0
投票

这里,如果

onsuccess
onupgradeneeded
之前被调用,那么即使你给它赋值,你的变量
store
还没有被实例化。也许这是你的情况的问题。

但是,如果可能的话,您应该尝试使用

let
const
,以获得更好的变量范围使用

© www.soinside.com 2019 - 2024. All rights reserved.