如何修改表格排序JS以获取td内span元素的原始值排序?
Got it, let's get your table sorting by the actual file size values stored in those hidden .sort-only spans instead of the visible text. Here's how to tweak your jQuery code:
1. Locate where your code extracts cell values for sorting
First, find the part of your sorting logic that grabs the value from the table cell. It probably looks something like this (common in custom jQuery sorting scripts):
// Original code that gets visible text var sortValue = $(tdElement).text().trim();
2. Modify to pull values from the hidden span
Replace the above line with code that targets the .sort-only span inside the cell, and convert the value to a number (since we're dealing with file size numbers, not strings):
// Updated code to get hidden numeric value var sortValue = parseFloat($(tdElement).find('.sort-only').text().trim()); // If your file sizes are integers (no decimals), use parseInt instead: // var sortValue = parseInt($(tdElement).find('.sort-only').text().trim(), 10);
3. Ensure your comparison logic uses numeric sorting
Double-check that your sorting comparison function treats these values as numbers, not strings. For example, a basic ascending sort comparison would look like:
function compareValues(a, b) { // a and b are the sortValue values from two cells return a - b; // Swap to b - a for descending sort }
If you're using a plugin like Tablesorter
If you're relying on a pre-built plugin (like jQuery Tablesorter), you'll need to define a custom parser for your file size column:
// Add a custom parser for file size values $.tablesorter.addParser({ id: 'fileSize', is: function() { return false; }, // Don't auto-detect, apply manually format: function(text, table, cell) { // Pull the numeric value from the hidden span return parseFloat($(cell).find('.sort-only').text().trim()); }, type: 'numeric' // Tell the sorter this is a number }); // Initialize the table with the custom parser for your target column $('your-table-selector').tablesorter({ headers: { 3: { // Replace with the index of your file size column (0-based) sorter: 'fileSize' } } });
This way, your table will sort using the raw numeric file size values from the hidden spans instead of the formatted text displayed to users.
内容的提问来源于stack exchange,提问作者mudraya katusha

