You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过HTML链接按ID获取JSON对象并展示(含SessionStorage)

Hey Steve, let's break down how to implement this feature step by step. Here's a complete solution that matches your requirements:

1. Update Your Original HTML

First, we'll turn the cake title into a clickable element and add a data-id attribute to link it to the corresponding JSON object's ID. This helps us identify which cake the user clicked on:

<div class="col">
  <!-- team-img -->
  <div class="team-block">
    <div class="team-content">
      <!-- Convert the static heading to a clickable link with data-id -->
      <a href="info.html" class="cake-link" data-id="1">
        <h4 class="text-white mb0">Chocolate Cake </h4>
      </a>
      <p class="team-meta">Lar...</p>
    </div>
  </div>
</div>

Pro tip: Replace data-id="1" with the actual ID of your Chocolate Cake entry in the JSON dataset.

2. Add Click Handler & SessionStorage Logic

Next, we'll add JavaScript to capture the click event, fetch the matching JSON object, and store it in sessionStorage before redirecting. Add this script right before the closing </body> tag of your page (or in an external JS file):

// Replace this sample data with your actual JSON dataset
const cakeDatabase = [
  {
    id: 1,
    name: "Chocolate Cake",
    description: "Rich, moist chocolate cake with dark chocolate ganache frosting",
    ingredients: ["All-purpose flour", "Cocoa powder", "Granulated sugar", "Eggs", "Unsalted butter"],
    meta: "Lar..."
  },
  {
    id: 2,
    name: "Vanilla Bean Cake",
    description: "Light, fluffy vanilla sponge with vanilla buttercream",
    ingredients: ["All-purpose flour", "Granulated sugar", "Eggs", "Unsalted butter", "Vanilla bean paste"],
    meta: "..."
  }
];

// Attach click listeners to all cake links
document.querySelectorAll('.cake-link').forEach(link => {
  link.addEventListener('click', function(e) {
    e.preventDefault(); // Stop the immediate page jump first
    
    // Get the cake ID from the link's data attribute
    const targetCakeId = parseInt(this.dataset.id);
    
    // Find the matching cake object in our JSON data
    const selectedCake = cakeDatabase.find(cake => cake.id === targetCakeId);
    
    if (selectedCake) {
      // Store the cake data in sessionStorage (needs to be a string)
      sessionStorage.setItem('selectedCake', JSON.stringify(selectedCake));
      
      // Now navigate to info.html
      window.location.href = this.href;
    } else {
      console.error(`Couldn't find cake with ID: ${targetCakeId}`);
    }
  });
});

Key details:

  • e.preventDefault() ensures we handle data storage before the page redirects
  • sessionStorage only stores strings, so we use JSON.stringify() to convert the object
  • The data-id attribute creates a clean link between the UI element and our JSON data

3. Build info.html to Display the Stored Data

Finally, create the info.html page to retrieve the data from sessionStorage and render it to the user:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cake Details</title>
  <style>
    .cake-details {
      max-width: 700px;
      margin: 3rem auto;
      padding: 2rem;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .ingredients-list {
      list-style: disc;
      padding-left: 1.5rem;
      margin: 1rem 0;
    }
  </style>
</head>
<body>
  <div class="cake-details">
    <h2 id="cake-title"></h2>
    <p id="cake-desc"></p>
    <h3>Ingredients:</h3>
    <ul class="ingredients-list" id="cake-ingredients"></ul>
    <p id="cake-meta"></p>
  </div>

  <script>
    // Retrieve the stored cake data from sessionStorage
    const selectedCake = JSON.parse(sessionStorage.getItem('selectedCake'));
    
    if (selectedCake) {
      // Populate the page with cake details
      document.getElementById('cake-title').textContent = selectedCake.name;
      document.getElementById('cake-desc').textContent = selectedCake.description;
      
      // Render the ingredients list
      const ingredientsContainer = document.getElementById('cake-ingredients');
      selectedCake.ingredients.forEach(ingredient => {
        const listItem = document.createElement('li');
        listItem.textContent = ingredient;
        ingredientsContainer.appendChild(listItem);
      });
      
      document.getElementById('cake-meta').textContent = selectedCake.meta;
      
      // Optional: Clear the sessionStorage after displaying (so data doesn't persist)
      // sessionStorage.removeItem('selectedCake');
    } else {
      // Handle cases where user visits info.html directly
      document.querySelector('.cake-details').innerHTML = '<p>No cake selected. Please go back and choose a cake to view details.</p>';
    }
  </script>
</body>
</html>

Notes for this page:

  • JSON.parse() converts the stored string back into a usable JavaScript object
  • We added fallback content for users who navigate directly to info.html without selecting a cake
  • The optional sessionStorage.removeItem() line ensures the data doesn't stick around after the user views the details

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:49:18