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

如何为表格行添加点击事件,实现按ID跳转至下一页?

Complete Your Row Click Navigation with window.location

Looks like you're almost there! You've got the row click handlers set up to grab the ID from the first cell—now let's finish the navigation part.

Here's the full, completed code with explanations:

function addRowHandlers() { 
  var table = document.getElementById("employee-click"); 
  var rows = table.getElementsByTagName("tr"); 
  
  // Loop through each row in the table
  for (var i = 0; i < rows.length; i++) { 
    var currentRow = table.rows[i]; 
    
    // Create a closure to preserve the row reference for each click handler
    var createClickHandler = function(row) { 
      return function() { 
        // Get the first cell's content (your ID)
        var cell = row.getElementsByTagName("td")[0]; 
        var id = cell.innerHTML.trim(); // Trim whitespace to avoid issues
        
        // Navigate to your details page, passing the ID
        // Replace "details.html" with your actual target page URL
        window.location.href = `details.html?id=${id}`; 
        
        // Alternative: If your URL uses the ID as a path segment (e.g., /details/123)
        // window.location.href = `details/${id}`; 
      }; 
    }; 
    
    // Attach the click handler to the current row
    currentRow.onclick = createClickHandler(currentRow); 
  } 
}

Key Adjustments & Notes:

  • Target Page URL: Swap out "details.html" with the actual URL of your details page (like employee-details.html or whatever you're using).
  • ID Parameter: If your details page expects the ID under a different query parameter name (not id), change it—for example, ?employeeId=${id}.
  • URL Format: Use the path segment version (the commented-out line) if your routing uses clean URLs instead of query parameters.
  • Sanitization: If your ID might contain special characters (like spaces or symbols), sanitize it further to ensure valid URLs:
    window.location.href = `details.html?id=${encodeURIComponent(id)}`;
    
  • Load Timing: Make sure you call addRowHandlers() after the table has loaded (either at the end of your HTML body, or inside a DOMContentLoaded event listener) so the table element exists when the function runs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:38:54