2017-05-26 94 views
0

我來到這個JS小提琴,這是偉大的。我需要做些什麼修改才能在頁面加載時以降序對第三列進行排序?jQuery排序表 - 在加載更改訂單

$(document).on('click', 'th', function() { 
    var table = $(this).parents('table').eq(0); 
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index())); 
    this.asc = !this.asc; 
    if (!this.asc) { 
    rows = rows.reverse(); 
    } 
    table.children('tbody').empty().html(rows); 
}); 

function comparer(index) { 
    return function(a, b) { 
    var valA = getCellValue(a, index), 
     valB = getCellValue(b, index); 
    return $.isNumeric(valA) && $.isNumeric(valB) ? 
     valA - valB : valA.localeCompare(valB); 
    }; 
} 

function getCellValue(row, index) { 
    return $(row).children('td').eq(index).text(); 
} 

Here is the link to the Fiddle.

許多在此先感謝。

回答

1

只要把你的排序邏輯在一個單獨的功能,並呼籲$該函數(文件)。就緒()

$(document).ready(function() { 
    sort(); 
}); 

$(document).on('click', 'th', function() { 
    sort(); 
}); 

function sort() { 
    var table = $('table').eq(0); 
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index())); 
    this.asc = !this.asc; 
    if (!this.asc) { 
     rows = rows.reverse(); 
    } 
    table.children('tbody').empty().html(rows); 
} 

function comparer(index) { 
    return function(a, b) { 
    var valA = getCellValue(a, index), 
     valB = getCellValue(b, index); 
    return $.isNumeric(valA) && $.isNumeric(valB) ? 
     valA - valB : valA.localeCompare(valB); 
    }; 
} 

function getCellValue(row, index) { 
    return $(row).children('td').eq(index).text(); 
}