JavaScript实现表格Success、Fail、Time列换行显示求助
Hey there! Let's get your table's Success, Fail, and Time columns displaying content with line breaks properly. Here's a step-by-step fix tailored to your code:
Key Issues in the Original Code
- Your current code iterates over object keys directly, which can lead to column misalignment since object key order isn't guaranteed in older JavaScript environments.
- There's no logic to target specific columns for line break formatting.
Modified Solution Code
HTML (with styling for better readability)
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Formatted Table</title> <style> #my-table { border-collapse: collapse; width: 100%; margin: 20px 0; } #my-table th, #my-table td { border: 1px solid #ddd; padding: 10px; } #my-table th { background-color: #f5f5f5; text-align: left; } /* Ensure line breaks render correctly */ #my-table td { white-space: pre-line; } </style> </head> <body> <table id="my-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Mobile Number</th> <th>Status</th> <th>Success</th> <th>Failed</th> <th>Time</th> </tr> </thead> </table> </body> </html>
JavaScript (with line break logic)
var responseList = [{ "summary": { "id": 898, "name": "Ben", "number": "399468789", "status": "fail", "success": "2, 5, 7", // Example: Multiple values separated by commas "fail": "1, 4", "created_at": "2020-07-10\n14:02:13" // Example: Line break in timestamp } }]; var table = document.querySelector('#my-table'); var tbody = document.createElement('tbody'); table.appendChild(tbody); // Define which fields need line break formatting const lineBreakFields = ['success', 'fail', 'created_at']; // Match the order of your table headers to avoid column misalignment const orderedFieldKeys = ['id', 'name', 'number', 'status', 'success', 'fail', 'created_at']; for (var i = 0; i < responseList.length; i++) { var tr = tbody.insertRow(); var summary = responseList[i]["summary"]; orderedFieldKeys.forEach(key => { var td = tr.insertCell(); let cellValue = summary[key]; // Apply line breaks only to targeted columns if (lineBreakFields.includes(key) && typeof cellValue === 'string') { // Replace commas + spaces with HTML line breaks cellValue = cellValue.replace(/, /g, '<br>'); // Replace raw newlines with HTML line breaks cellValue = cellValue.replace(/\n/g, '<br>'); } td.innerHTML = cellValue; }); }
What This Does
- Column Alignment: Using an ordered array of keys ensures your table cells match the header order perfectly, no more random column shifts.
- Targeted Line Breaks: We check if the current field is in our
lineBreakFieldslist, then convert common separators (commas, raw newlines) into HTML<br>tags to create visible line breaks. - CSS Support: The
white-space: pre-linestyle ensures any line breaks (from<br>or raw newlines) are rendered correctly in the table cells.
内容的提问来源于stack exchange,提问作者adnan khan
相关产品推荐
相关产品推荐

