Auto sort the table using sorttable.js

2019-05-01 01:28发布

问题:

I am trying to use this script to sort the html table: http://www.kryogenix.org/code/browser/sorttable/

JS code itself: http://www.kryogenix.org/code/browser/sorttable/sorttable.js

I used the customkey option and it works when I click the heading. I would like to auto sort based on that customkey when the page loads. How can I do that? I want to use this specific script. I tried window.onload but with no luck.

回答1:

After loading the page just trigger a click on the header column you want to sort. Try with following javascript code. I assume that there is only one table in the page. Perhaps you will need to be more specific using getElementsByTagName or with getElementById instead. The [1] is the column number. You don't need to attach a click handler before that because that task is done by the code of sorttable.js.

<script src="js/sorttable.js"></script>
<script>
    window.onload = function() {
        (document.getElementsByTagName( 'th' )[1]).click();
    };
</script>


回答2:

I solved this problem slightly different. On whatever table header I wanted clicked on the page load, I added data-autoclick="true". Then in my main application JavaScript, I added

<script>
    window.onload = function() {
        $('[data-autoclick="true"]').click();
    };
</script>


回答3:

How to use

table.sortable th:not(.sorttable_sorted):not(.sorttable_sorted_reverse):not(.sorttable_nosort):after { 
        content: " \25B4\25BE" 
    }

in dynamic table.