簡體   English   中英

使用本地存儲在單擊時將 JSON 數據從一頁傳遞到另一頁並顯示

[英]Pass and display JSON data from one page to another on click using local storage

我一直在嘗試使用本地存儲在單擊時從一頁到另一頁顯示 JSON 數據。

例如,用戶單擊一本書的特定圖像,然后將他們帶到 book.html 顯示圖像和書名的位置(來自 json 文件)

FIGMA 原型- https://www.figma.com/proto/VAFgj0JQVX0YLt3WyZ12el/Untitled?node-id=5%3A5&scaling=min-zoom

腳本.js

const petsData = [{
  name: "Story Book",
  species: "Jean Lumier", //THIS IS THE JSON FILE
  photo: "a.jpg"
},
{
  name: "Barksalot",
  species: "Dog",
  href:"href.img,
  photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"
},

];



function petTemplate(pet) {
  
return `
<div class ="image-grid">
   <div class="animal">
   
    <img class="pet-photo " src="${pet.photo}" >
   
      
       <div class="olay" onclick="location.href='${pet.href}';" style="cursor: pointer;">
       <div id="mydiv">
  
      <h2 class="pet-name">${pet.name}
      
      
      <h1 class="species">${pet.species}

      </div>
       <div></div></div>
      </div>
   </div>

  
`;
}

謝謝你。

我將其設置為一頁演示: https://stackblitz.com/edit/web-platform-uzc5rj

由於您的 JSON 沒有 ID,您可以在 book.html 鏈接中的數組中引用 position。 像這樣:

<a href='book.html?book=1'><img of book /></a>

然后在書中。html

<div id='book_details'></div>
   <script>
let bookData = localStorage.getItem('bookData');
 bookData = JSON.parse(bookData)

    const urlParams = new URLSearchParams(window.location.search);
    const bookPos = urlParams.get('book');
    
   
      let book = bookData[bookPos]
      let bookHtml =  `
    <div class ="book-html">
    <h1>${book.name}  </h1>
    <p>${book.species} </p>
    </div>
    `;
    
    document.getElementById('book_details').innerHTML = bookHtml;
 
  </script>
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM