2016-06-22 4 views
1

나는이 튜토리얼을 indexedDB를 사용하는 블로그에서 보았습니다. 나는 indexedDB에 익숙하지 않아 조금만 이해할 수 있습니다.삭제, 함수 제거, 작동하지 않는 것 같습니다

read, readAll 및 add와 같은 기타 기능이 제대로 작동하고 있습니다. 함수 제거가 작동하지 않는 동안. 이러한 기능은 버튼을 통해 onclick이라고합니다.

데이터 삭제를 클릭 할 때마다 버튼이 사라지고 아무런 변화가 없습니다.

HTML :

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <script type="text/javascript" src="index.js"></script> 
    <link rel="stylesheet" type="text/css" href="index.css" media="all"> 
    <title>Sample IndexedDB</title> 
</head> 

<body> 
    <button onclick="read()">Read </button> 
    <button onclick="readAll()">Read all </button> 
    <button onclick="add()">Add data </button> 
    <button onclick="remove()">Delete data </button> 
</body> 
</html> 

자바 스크립트 : 도움의 모든 종류가 매우 많이 감사합니다

 //prefixes of implementation that we want to test 
    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; 

    //prefixes of window.IDB objects 
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; 
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange 

    if (!window.indexedDB) { 
     window.alert("Your browser doesn't support a stable version of IndexedDB.") 
    } 

    const employeeData = [ 
     { id: "00-01", name: "gopal", age: 35, email: "[email protected]" }, 
     { id: "00-02", name: "prasad", age: 32, email: "[email protected]" } 
    ]; 
    var db; 
    var request = window.indexedDB.open("sampleDB", 3); 

    request.onerror = function(event) { 
     console.log("error: "); 
    }; 

    request.onsuccess = function(event) { 
     db = request.result; 
     console.log("success: "+ db); 
    }; 

    request.onupgradeneeded = function(event) { 
     var db = event.target.result; 
     var objectStore = db.createObjectStore("employee", {keyPath: "id"}); 

     for (var i in employeeData) { 
      objectStore.add(employeeData[i]); 
     } 
    } 

    function read() { 
     var transaction = db.transaction(["employee"]); 
     var objectStore = transaction.objectStore("employee"); 
     var request = objectStore.get("00-03"); 

     request.onerror = function(event) { 
      alert("Unable to retrieve daa from database!"); 
     }; 

     request.onsuccess = function(event) { 
      // Do something with the request.result! 
      if(request.result) { 
       alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email); 
      } 

      else { 
       alert("Kenny couldn't be found in your database!"); 
      } 
     }; 
    } 

    function readAll() { 
     var objectStore = db.transaction("employee").objectStore("employee"); 

     objectStore.openCursor().onsuccess = function(event) { 
      var cursor = event.target.result; 

      if (cursor) { 
       alert("Name for id " + cursor.key + " is " + cursor.value.name + ",\r\nAge: " + cursor.value.age + ",\r\nEmail: " + cursor.value.email); 
       cursor.continue(); 
      } 

      else { 
       alert("No more entries!"); 
      } 
     }; 
    } 

    function add() { 
     var request = db.transaction(["employee"], "readwrite") 
     .objectStore("employee") 
     .add({ id: "00-03", name: "Kenny", age: 19, email: "[email protected]" }); 

     request.onsuccess = function(event) { 
      alert("Kenny has been added to your database."); 
     }; 

     request.onerror = function(event) { 
      alert("Unable to add data\r\nKenny aready exist in your database! "); 
     } 
    } 

    function remove() { 
     var request = db.transaction(["employee"], "readwrite") 
     .objectStore("employee") 
     .delete("00-03"); 

     request.onsuccess = function(event) { 
      alert("Kenny's entry has been removed from your database."); 
     }; 
    } 

.

답변

2

확실하지가 도움이되지만 몇 가지가있는 경우 :

  • 당신은 일반적으로 배열 이상에서 사용하지 않으려는. For..in은 객체의 키를 반복하는 데 사용됩니다. 배열을 반복 할 때 for (var i = 0; i < arraylength; i ++)를 사용하십시오.
  • db.transaction ([ 'store'])과 같이 객체 저장소 주변의 대괄호는 선택 사항입니다. 너는 필요 없어. 실제로 코드를 일관성없이 사용하므로 코드를 읽기가 어렵습니다.
  • 'var db'변수를 사용하는 방식으로 사용해서는 안됩니다. 제거를 클릭 할 때 연결이 null이거나 닫힐 수 있습니다.
  • 할 수 있지만 onupgradeneeded 함수 내에서 데이터를 삽입하지 않는 것이 좋습니다. 업그레이드 필요 기능은 데이터베이스 스키마를 작성하거나 수정하기위한 것입니다. 대신 다른 기능을 사용해야합니다. 다른 함수를 직접 호출하면 indexedDB는 자동으로 onregradeneeded를 호출 한 다음 함수를 실행할 필요가 있는지 자동으로 결정합니다.
  • window.indexedDB = window.indexedDB || window.mozIndexedDB ...과 같은 접두사는 더 이상 필요하지 않습니다. indexedDB를 지원하는 모든 주요 브라우저는이 접두사를 삭제했습니다. 그냥 사용하십시오 window.indexedDB
  • 일부 기능에서만 request.onerror를 처리하는 이유가 확실하지 않습니다.
  • 'window'에 전역 변수 접두사를 붙일 필요는 없습니다. 예를 들어 window.indexedDB 대신 indexedDB을 직접 사용할 수 있습니다.
  • 일반적으로 저장소 위에 커서를 반복하는 readAll 함수의 컨텍스트 내에서 '경고'를 호출하지 않으려합니다. 경고가 차단 중입니다. 커서 반복은 비동기입니다.

어쨌든, 내 추측은 어떻게 든 버튼의 온 클릭 핸들러가 element.parentNode.removeChild(element) 유사 element.remove()를 호출한다는 것입니다. remove 함수의 이름을 변경하십시오.

또한 제거 할 onerror 핸들러를 추가하고 추가 한 후 개발자 도구의 오브젝트 저장소에있는 오브젝트를 볼 수 있는지 확인하십시오.

+0

안녕하세요! 답변 주셔서 감사합니다. 귀하의 추측은 옳은 것처럼 보였으며 이름을 바꿔 고정 시켰습니다. 또한, 코딩 스타일에 관해서는, 대부분의 코드는 튜토리얼에서 복사하여 붙여 넣기 만하면됩니다. 내가 열거 한 것을 메모 해 두겠습니다. – mtolingan

관련 문제