Home > Back-end >  How to display local storage to HTML page?
How to display local storage to HTML page?

Time:05-17

I have a project. It is about to people search something in search page and when they come back to home page, searching history will show on home page. I have pushed searching data to local storage, with key and value. The problem is I dont know how to show it to my html page. Have you worked with the same thing like me? Thanks a lot. Needs some comment to solve my problem.

<section >
<div >
        <h2 id="div_title" >検索履歴<span ></span></h2>
</div>
<ul >
    <li>
        <section id="list_box">
            <div >
                
            </div>
            <div >
                
            </div>
            <div >
                
            </div>
            <div >
                
            </div>
            <div >
                
            </div>
        </section>
    </li>
</ul>

And this is my script

<script type="text/javascript">
function getData() {
    return this.$storage.get('listKey');
}
window.onload = function () {
    const div = document.querySelectorAll("#list_box > div");
    const tdiv = div.parentNode;
    const data = getData();
    for (let i = 1; i< data.length; i  ) {
        tdiv.appendChild(div.cloneNode(true));
    }
    data.forEach((row, i) => Object.keys(row).forEach(prop => 
        tdiv.rows[i 1].querySelector('.'   prop).textContent = row[prop]);
    );
}

CodePudding user response:

document.querySelectorAll returns a NodeList, that's what you got wrong.

CodePudding user response:

In your code, you're referencing local storage as this.$storage, I'm not sure what wrapper this is or from what library, but I'm going to assume you want to interact with HTML5 localStorage.

localStorage stores strings so if you want to store a more complex data structure, you need to transform it.

You can transform an array or an object using the JSON.stringify method.

To get the content of local storage at a later time and if IS NOT a plain string, you would use the JSON.parse method.

In the code below you can see that getFromLocalStorage and saveToLocalStorage use the JSON.parse and JSON.stringify methods respectively.

  <script type="text/javascript">
      function getFromLocalStorage(localStorageKey = "items") {
        return JSON.parse(localStorage.getItem(localStorageKey)) || [];
      }

      function saveToLocalStorage(localStorageKey = "items", value) {
        const items = getFromLocalStorage();
        const newItems = [...items, value];

        localStorage.setItem("items", JSON.stringify(newItems));
      }

      window.onload = function () {
        const items = getFromLocalStorage();

        items.forEach((item) => {
         // do something with items.
        });
      };
    </script>
  • Related