如何修改表格生成函数使姓名同时作为URL链接
Got it, let's tweak your function so the full names become clickable links. I'll also fix a couple of small issues in your original code that were breaking the table structure. Here's how to do it:
Step-by-Step Modifications
Wrap the full name in an HTML
<a>tag
We'll use the URL associated with each member (I assume this is stored inmembers[r].urlsince you mentioned the table includes URL info) as the link target.Fix table structure bugs
Your original code had incorrect closing<tr>tags and usedJSON.stringify()on the HTML string (which would display escaped text instead of a real table). We'll correct those.Clean up name formatting
We'll make the middle name handling more elegant to avoid extra spaces when there's no middle name.
Modified Full Code
var members = data.results[0].members; createTable(members); function createTable(members) { // Start with a proper table header for clarity var table = `<thead> <tr> <th>Full name</th> <th>Party</th> <th>State</th> <th>Seniority</th> <th>Votes with Party %</th> </tr> </thead> <tbody>`; for (var r = 0; r < members.length; r++) { // Build full name with clean middle name handling var fullName = `${members[r].first_name}, ${members[r].middle_name ? members[r].middle_name + ' ' : ''}${members[r].last_name}`; table += "<tr>"; // Turn name into a clickable link table += `<td><a href="${members[r].url}" target="_blank">${fullName}</a></td>`; table += `<td>${members[r].party}</td>`; table += `<td>${members[r].state}</td>`; table += `<td>${members[r].seniority}</td>`; // Handle missing vote percentage if (members[r].votes_with_party_pct === undefined) { table += "<td>-</td>"; } else { table += `<td>${members[r].votes_with_party_pct}%</td>`; } table += "</tr>"; // Correctly close the table row } table += "</tbody>"; // Assign the raw HTML string directly (no JSON.stringify!) document.getElementById("house-data").innerHTML = table; }
Key Changes Explained
- Clickable Names: The full name is now wrapped in
<a href="${members[r].url}">...</a>. Thetarget="_blank"attribute opens the link in a new tab (you can remove this if you prefer links open in the same tab). - Proper Table Structure: Added a
<thead>with clear column headers, and fixed the closing</tr>tag (your original code was using<tr>again, which broke the table). - Cleaner Name Formatting: Used a ternary operator to only add the middle name and space if it exists, so no extra spaces show up when there's no middle name.
- Fixed HTML Rendering: Removed
JSON.stringify()from the final assignment — this was converting your HTML into an escaped string, which is why your table wasn't displaying correctly before.
内容的提问来源于stack exchange,提问作者Maivan Fildero

