简体   繁体   中英

Javascript To-Do List with IndexedDB shows always the same Date for every Item after adding an Item to the list

I created a To-Do List with Javascript, HTML and IndexedDB to store the Items in the database so that when I refresh the Browser the items won't get deleted. I also want to add the Date to the Items, but when I press the button to add an Item, the Date always becomes the same as the other items, but that's not how it should work:

1个

I want that the date is always as I choose it to be for every Item.

It's the first time i ask a question here, so i hope it's not completely wrong how I do it. Here is the whole code, i think the problem lays in the renderTodo(row)-function but I am not sure:

<!DOCTYPE html>
<html>
<head>

    <title>ToDo-List IndexedDB</title>
    <script type="text/javascript">

    
      var html5rocks = {};
    window.indexedDB = window.indexedDB || window.webkitIndexedDB ||
                    window.mozIndexedDB;


    if ('webkitIndexedDB' in window) 
    {
        window.IDBTransaction = window.webkitIDBTransaction;
        window.IDBKeyRange = window.webkitIDBKeyRange;
    }

    html5rocks.indexedDB = {};
    html5rocks.indexedDB.db = null;


    html5rocks.indexedDB.onerror = function(e) 
    {
        console.log(e);
    };

    html5rocks.indexedDB.open = function() 
    {
      var version = 1;
      var request = indexedDB.open("todos", version);

      // We can only create Object stores in a versionchange transaction.
      request.onupgradeneeded = function(e) 
      {
        var db = e.target.result;

        // A versionchange transaction is started automatically.
        e.target.transaction.onerror = html5rocks.indexedDB.onerror;

        if(db.objectStoreNames.contains("todo")) 
        {
          db.deleteObjectStore("todo");
        }

        var store = db.createObjectStore("todo",
          {keyPath: "timeStamp"});
      };

      request.onsuccess = function(e) 
      {
          html5rocks.indexedDB.db = e.target.result;
          html5rocks.indexedDB.getAllTodoItems();
      };

      request.onerror = html5rocks.indexedDB.onerror;
    };

    html5rocks.indexedDB.addTodo = function(todoText) 
    {

      var db = html5rocks.indexedDB.db;
      var trans = db.transaction(["todo"], "readwrite");
      var store = trans.objectStore("todo");

      var data = 
      {
          "text": todoText,
          "timeStamp": new Date().getTime()
      };

      var request = store.put(data);

      request.onsuccess = function(e) 
      {
          html5rocks.indexedDB.getAllTodoItems();
      };

      request.onerror = function(e) 
      {
          console.log("Error Adding: ", e);
      };
    };

    html5rocks.indexedDB.deleteTodo = function(id) 
    {
      var db = html5rocks.indexedDB.db;
      var trans = db.transaction(["todo"], "readwrite");
      var store = trans.objectStore("todo");

      var request = store.delete(id);

      request.onsuccess = function(e) 
      {
          html5rocks.indexedDB.getAllTodoItems();
      };

      request.onerror = function(e) 
      {
          console.log("Error Adding: ", e);
      };
    };

    html5rocks.indexedDB.getAllTodoItems = function() 
    {

      var todos = document.getElementById("list");
      todos.innerHTML = "";

      var db = html5rocks.indexedDB.db;
      var trans = db.transaction(["todo"], "readwrite");
      var store = trans.objectStore("todo");

      // Get everything in the store;
      var keyRange = IDBKeyRange.lowerBound(0);
      var cursorRequest = store.openCursor(keyRange);


      cursorRequest.onsuccess = function(e) 
      {
          var result = e.target.result;
          if(!!result == false)
            return;

          renderTodo(result.value);
          result.continue();
      };

      cursorRequest.onerror = html5rocks.indexedDB.onerror;
    };


    function renderTodo(row) 
    {

        const dt = getDatePickerDate('date');


        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };


        if(row.text.trim() == "")
        {

            document.getElementById("ausgabe").innerHTML = "<br/><br/> Have to enter a task!";
        }

        else 
        {


            document.getElementById("ausgabe").innerHTML = "";


            var input_date = "  " + dt.toLocaleDateString([], options) + ": " + row.text; 


            var list = document.getElementById("list");
            
            var container = document.createElement("container");
           
            var button = document.createElement("button");
            button.type = "button";
            button.innerText = "X";
            var a = document.createElement("a");


            button.addEventListener("click", function() 
            {
                html5rocks.indexedDB.deleteTodo(row.timeStamp);
            },  false);

            
            container.appendChild(document.createElement("br"));
            container.appendChild(document.createElement("br"));
            container.appendChild(button);
            container.appendChild(document.createTextNode(input_date));
            container.appendChild(document.createElement("br"));
            list.appendChild(container);

       }
    }

    function getDatePickerDate(elementId) 
    {

        const value = document.getElementById(elementId).value
        const [year, month, day] = value.split('-');
        return new Date(year, month - 1, day);

    }

    function addTodo() 
    {
        var todo = document.getElementById("todo");
        html5rocks.indexedDB.addTodo(todo.value);
        todo.value = "";
    }

    function init() 
    {
        html5rocks.indexedDB.open();
    }

    window.addEventListener("DOMContentLoaded", init, false);


    </script>

</head>

<body style="background-color:#647e7f">

  <h1 style="position:absolute;top:10px;left:10px;">ToDo Liste </h1>

  <br /><br /><br /> <br /><br /> <br /><br /><h2>Activity:</h2><br /><br />


  <textarea id="todo" name="text_input" rows="10" cols="50">

  </textarea>

  <br />

  <input type="date" id="date">

  <input type="button" value="add" id = "speichern" onclick="addTodo()" />

  <br />


  <p id = "ausgabe" ></p>

  <container id = "list" ></container>


</body>
</html>

It is because your code is synchronous. Each addTodo happens sequentially and synchronous

To get different dates, Make functions async, await each transaction to database (it will take time)

html5rocks.indexedDB.addTodo = async function(...
...
var request = await store.put(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM