如何根据值关联修改表格颜色?附后端填充表格的JS函数
Alright, let's figure out how to add conditional coloring to your proposal table based on specific values. Here's a straightforward way to modify your existing AllProposals() function to get this working:
Step 1: Define Your Coloring Logic
First, decide which data field you want to use to trigger color changes (e.g., a Status, Priority, or IsApproved field from your proposal data). Then map those values to CSS classes or inline styles.
Step 2: Modify Your AJAX Success Handler
Update your loop to apply the appropriate styling when generating table rows or cells. Here's the modified code with comments explaining each part:
function AllProposals() { let getProposalsUrl = '/proposals/index'; $.ajax({ url: getProposalsUrl, contentType: 'application/json; charset=utf-8', type: 'GET', dataType: 'json', processData: false, success: function (data) { $("#proposals").empty(); var list = data; for (var i = 0; i <= list.length - 1; i++) { // 👇 Replace `Status` with your actual target field (e.g., Priority, IsActive) const proposalStatus = list[i].Status; let rowClass = ''; // Map field values to CSS classes (use Bootstrap classes or your own) switch(proposalStatus) { case 'Approved': rowClass = 'table-success'; // Light green background break; case 'Pending': rowClass = 'table-warning'; // Light yellow background break; case 'Rejected': rowClass = 'table-danger'; // Light red background break; default: rowClass = ''; // No styling for unrecognized values } // Generate table row with the conditional class var tableData = '<tr class="' + rowClass + '">' + '<td class="proposalId">' + list[i].Id + '</td>' + '<td>' + (list[i].Title || 'No Title') + '</td>' + // Replace with your actual columns '<td>' + proposalStatus + '</td>' + // Add your remaining columns here... '</tr>'; $("#proposals").append(tableData); } }, // Add error handling for debugging error: function(xhr, status, error) { console.error('Error fetching proposals:', error); } }); }
Step 3: Add Custom CSS (If Not Using Bootstrap)
If you aren't using Bootstrap's built-in table classes, define your own styles in a CSS file:
/* Custom table row styles */ .table-success { background-color: #d4edda; } .table-warning { background-color: #fff3cd; } .table-danger { background-color: #f8d7da; }
Alternative: Color Specific Cells Instead of Rows
If you only want to color a single cell (e.g., the status column) instead of the entire row, adjust the code to apply the class to that specific <td>:
// Replace the status column line with this: '<td class="' + rowClass + '">' + proposalStatus + '</td>'
Notes
- Replace
Statuswith the actual field name from your JSON data that you want to base coloring on. - Adjust the
switchcase values to match your data's possible values (e.g.,High/Medium/Lowfor priority). - For boolean values (like
IsApproved: true), use anif/elsestatement instead of aswitch.
内容的提问来源于stack exchange,提问作者Silco

