【问题标题】:Pass and display JSON data from one page to another on click using local storage使用本地存储在单击时将 JSON 数据从一个页面传递和显示到另一个页面
【发布时间】:2021-08-11 14:46:54
【问题描述】:

我一直在尝试使用本地存储在点击时将 JSON 数据从一个页面显示到另一个页面。

例如,用户单击一本书的特定图像,然后将他们带到 book.html 显示图像和书名的位置(来自 json 文件)

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

script.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>

  
`;
}

谢谢。

【问题讨论】:

  • JSON 来自哪里?
  • 你都在用什么?这是一个节点应用程序

标签: javascript html css json


【解决方案1】:

我将其设置为单页演示:https://stackblitz.com/edit/web-platform-uzc5rj

由于您的 JSON 没有 ID,您可以在 book.html 链接中引用数组中的位置。像这样:

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

然后在book.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>
    

【讨论】:

  • 抱歉,我想使用本地存储
  • 我使用了与您发送的完全相同的代码,但页面只是空的。点击应该是这样的吗? &lt;div class="olay" onclick="location.href='book.html?book=1';" style="cursor: pointer;"&gt;
  • 在你的代码中加入一些 console.log() 语句来确定:你得到 JSON 数据了吗?你得到 bookPos 变量好吗?在这一点上,事情不起作用。是的,您的 onclick 看起来不错
  • 我看起来我获取 json 数据正常,但我获取 getTemplateFor 未定义错误可以运行您发布的代码并查看它是否运行正常?
  • 我在上面简化了一点,做了一个单页演示:stackblitz.com/edit/js-yx6yye?file=index.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 2020-04-02
相关资源
最近更新 更多