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

如何使用JS将表格选中行的指定数据传递至另一页面

Got it, let's tackle this step by step. You want to click an image link in your table, pass the entire row's data to another page, and display it there—here's how to do it cleanly with JavaScript:

Solution Breakdown

We’ll split this into two parts: handling clicks on the source page to collect row data and navigate, and retrieving/displaying data on the target page.

Step 1: Modify Your Source Table & Add Click Handling

We’ll use event delegation (more efficient than binding events to every link) to capture clicks on image links, collect the row’s data, and redirect to the target page.

Source Page Code

<table style="width:100%" id="ex-table">
  <thead>
    <tr>
      <th>Image</th>
      <th>Product Name</th>
      <th>Price</th>
      <th>Category</th>
    </tr>
  </thead>
  <tbody>
    <!-- Example row; repeat for your actual data -->
    <tr>
      <td><a href="#"><img src="product1.jpg" alt="Wireless Headphones"></a></td>
      <td>Wireless Headphones</td>
      <td>$99.99</td>
      <td>Electronics</td>
    </tr>
    <tr>
      <td><a href="#"><img src="product2.jpg" alt="Stainless Steel Bottle"></a></td>
      <td>Stainless Steel Water Bottle</td>
      <td>$24.99</td>
      <td>Home Goods</td>
    </tr>
  </tbody>
</table>

<script>
// Attach one click listener to the entire table (event delegation)
document.getElementById('ex-table').addEventListener('click', function(e) {
  // Check if we clicked an image-wrapping link
  const imageLink = e.target.closest('a');
  if (!imageLink || !imageLink.querySelector('img')) return;

  // Stop the default link jump behavior
  e.preventDefault();

  // Get the parent row of the clicked link
  const row = imageLink.closest('tr');
  if (!row) return;

  // Collect all relevant data from the row
  const cells = row.querySelectorAll('td');
  const rowData = {
    imageSrc: imageLink.querySelector('img').src,
    imageAlt: imageLink.querySelector('img').alt,
    productName: cells[1].textContent.trim(),
    price: cells[2].textContent.trim(),
    category: cells[3].textContent.trim()
  };

  // Option 1: Pass data via URL parameters (simple, ideal for small data)
  const urlParams = new URLSearchParams(rowData);
  window.location.href = `target-page.html?${urlParams.toString()}`;

  // Option 2: Use localStorage (better for large/complex data)
  // localStorage.setItem('selectedRowData', JSON.stringify(rowData));
  // window.location.href = 'target-page.html';
});
</script>

Key Notes:

  • Event Delegation: This works even if you add rows dynamically later—no need to re-bind events to new links.
  • Data Collection: Adjust the cells[index] values to match your table’s column order (indexes start at 0).
  • Transfer Options:
    • URL Parameters: Automatically handles special character encoding, perfect for simple data sets.
    • localStorage: Great for larger data (like long product descriptions), but remember to clear it after use to avoid leftover data.

Step 2: Retrieve & Display Data on the Target Page

On your target page, we’ll fetch the passed data and render it dynamically.

Target Page Code (e.g., target-page.html)

<!DOCTYPE html>
<html>
<head>
  <title>Selected Item Details</title>
</head>
<body>
  <h1>Selected Item Details</h1>
  <div id="detail-container" style="max-width: 500px; margin: 20px 0;"></div>

  <script>
    // Option 1: Get data from URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const selectedData = {
      imageSrc: urlParams.get('imageSrc'),
      imageAlt: urlParams.get('imageAlt'),
      productName: urlParams.get('productName'),
      price: urlParams.get('price'),
      category: urlParams.get('category')
    };

    // Option 2: Get data from localStorage
    // const selectedData = JSON.parse(localStorage.getItem('selectedRowData'));
    // // Clear localStorage to avoid showing old data on refresh
    // localStorage.removeItem('selectedRowData');

    // Render data safely into the page
    const container = document.getElementById('detail-container');
    
    // For security, use textContent for user-generated text instead of innerHTML directly
    const img = document.createElement('img');
    img.src = selectedData.imageSrc;
    img.alt = selectedData.imageAlt;
    img.style.maxWidth = '100%';
    
    const productName = document.createElement('h2');
    productName.textContent = selectedData.productName;
    
    const price = document.createElement('p');
    price.innerHTML = `<strong>Price:</strong> ${selectedData.price}`;
    
    const category = document.createElement('p');
    category.innerHTML = `<strong>Category:</strong> ${selectedData.category}`;
    
    container.append(img, productName, price, category);
  </script>
</body>
</html>

Key Notes:

  • Security: Using textContent for text fields prevents XSS attacks if your data includes user-generated content.
  • Cleanup: If using localStorage, always remove the item after retrieving it—otherwise, refreshing the target page will show the last selected data.
  • Path Checks: Ensure your image URLs are absolute, or that relative paths work from the target page’s location.

Troubleshooting Tips

  • If row data isn’t collecting correctly: Double-check the cells[] index numbers to match your table’s columns.
  • If target page gets no data: Verify you’re using the same transfer method (URL params vs localStorage) on both pages, and that keys match exactly.
  • If images break: Confirm the imageSrc path is valid from the target page’s directory.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:01:57