如何为表格行添加点击事件,实现按ID跳转至下一页?
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 (likeemployee-details.htmlor 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 aDOMContentLoadedevent listener) so the table element exists when the function runs.
内容的提问来源于stack exchange,提问作者adam
相关产品推荐
相关产品推荐

