如何判断DataTable中选中行的状态是否全部满足指定条件?
Solution to Validate All Selected Rows' Status
Hey there! Let's fix this logic issue you're having. The problem with your current code is that it only grabs the status from the first selected row and loops through individual characters of that single status string instead of checking all selected rows. Here's how to implement your required logic properly:
Fixed Code
$('#dataTable tbody').on('click', 'tr', function () { // Get all selected rows' data (not just the first one) const selectedRows = table.rows('.selected').data(); if (selectedRows.length === 0) return; // Exit early if no rows are selected // Extract the status column (index 2) from each selected row into an array const statuses = selectedRows.map(row => row[2]); // Check conditions in strict-to-loose order to avoid false matches const allUp = statuses.every(status => status === "Up"); const allUpOrPaused = statuses.every(status => status === "Up" || status === "Paused"); const allStopped = statuses.every(status => status === "Stopped"); if (allUp) { console.log("all up"); } else if (allUpOrPaused) { console.log("all up or paused"); } else if (allStopped) { console.log("all stopped"); } else { console.log("do nothing"); } });
Key Improvements & Explanations
- Get all selected rows: Using
table.rows('.selected').data()instead oftable.row('.selected')retrieves data for every selected row, not just the first. - Clean status array: The
map()method extracts the status value (from column index 2) into a dedicated array of status strings, making it easy to validate. - Condition order: We check the strictest condition (
allUp) first. Since all rows being "Up" would also satisfy the "Up or Paused" condition, this ensures we get the correct, specific output. - Empty selection handling: The early exit if no rows are selected prevents unnecessary logic execution.
Why Your Original Code Failed
Your original code had two critical issues:
table.row('.selected').data()[2]only fetched the status from the first selected row, ignoring any others.$.each(rowsStatus, ...)was looping through each character of that single status string (sincerowsStatuswas a string, not an array of statuses), which caused repeated "up" logs.
内容的提问来源于stack exchange,提问作者qweq
相关产品推荐
相关产品推荐

