jsTableSorter插件不适用于样式

时间:2014-06-09 17:12:51

标签: javascript tablesorter

我正在尝试使用带有 Blue 主题的jsTableSorter插件。不幸的是,以下代码不适用于该样式。你能帮我找一下这个问题。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="shortcut icon" href="http://i56.servimg.com/u/f56/18/49/06/85/pcicon10.png" />
    <title>
      PokéClub! Ranking
    </title>
    <link rel="stylesheet" type="text/css" href="http://dl.dropboxusercontent.com/s/5sckq157asnl68z/pcranking.css" />    
    <link rel="stylesheet" type="text/css" href="http://dl.dropboxusercontent.com/s/799k8f76ukikxa8/style.css" />
    <script type="text/javascript" src="http://dl.dropboxusercontent.com/s/5c8cuzcww0bjua4/jquery-latest.js"></script>
    <script type="text/javascript" src="http://dl.dropboxusercontent.com/s/2gbxvhkskdsch5p/jquery.tablesorter.js"></script>
    <script type="text/javascript">
      var jsonData = JSON.stringify([{
    trainer: "CLBGM",
    win: 9,
    loss: 13
}, {
    trainer: "Galakthor",
    win: 26,
    loss: 18
}, {
    trainer: "JOOY",
    win: 20,
    loss: 21
}, {
    trainer: "Matiaz98",
    win: 18,
    loss: 12
}, {
    trainer: "PokeCraftMariano",
    win: 16,
    loss: 14
}, {
    trainer: "Rockemc",
    win: 23,
    loss: 17
}]);

var ScoreTable = (function () {
    function scoreTable(trainer, win, loss) {
        this.position = '';
        this.trainer = trainer;
        this.win = win;
        this.loss = loss;
        this.battles = this.win + this.loss;
        this.winrate = this.win / this.battles;
        this.rating = this.win * 7 - this.loss * 3;
    }
    return scoreTable;
})();

function getColumn(value) {
    return $('<td>' + value + '</td>');
}

function addRow(item) {
    var row = $("<tr />");
    $("tbody").append(row);

    row.append(getColumn(item.position));
    row.append(getColumn(item.trainer));
    row.append(getColumn(item.battles));
    row.append(getColumn(item.win));
    row.append(getColumn(item.loss));
    row.append(getColumn((item.winrate * 100).toFixed(0) + '%'));
    row.append(getColumn(item.rating));
}

function populate(data) {
    for (var i = 0; i < data.length; i++) {
        var item = new ScoreTable(data[i].trainer, data[i].win, data[i].loss);
        addRow(item);
    }
}

$(document).ready(function () {
    method1Parse();
    //method2Ajax();
    sort();
});

function method1Parse() {
    var parsedData = $.parseJSON(jsonData);
    populate(parsedData);
}

function method2Ajax() {
    // jsFiddle handles AJAX requests differently (returns the value that you sent)  you may find more details in http://doc.jsfiddle.net/use/echo.html

    $.ajax({
        url: '/echo/json/',
        type: "post",
        dataType: "json",
        data: {
            json: jsonData,
            delay: 1
        },
        success: function (data) {
            populate(data);
        }
    });
}

$.tablesorter.addWidget({
    id: "numbering",
    format: function(table) {
        var c = table.config;
        $("tr:visible", table.tBodies[0]).each(function(i) {
            $(this).find('td').eq(0).text(i + 1);
        });
    }
});

function sort() {
    $('table').tablesorter({

        // *** APPEARANCE ***
        // Add a theme - try 'blackice', 'blue', 'dark', 'default'
        //  'dropbox', 'green', 'grey' or 'ice'
        // to use 'bootstrap' or 'jui', you'll need to add the "uitheme"
        // widget and also set it to the same name
        // this option only adds a table class name "tablesorter-{theme}"
        theme: 'default',

        // fix the column widths
        widthFixed: false,

        // Show an indeterminate timer icon in the header when the table
        // is sorted or filtered
        showProcessing: false,

        // header layout template (HTML ok); {content} = innerHTML,
        // {icon} = <i/> (class from cssIcon)
        headerTemplate: '{content}',

        // return the modified template string
        onRenderTemplate: null, // function(index, template){ return template; },

        // called after each header cell is rendered, use index to target the column
        // customize header HTML
        onRenderHeader: function (index) {
            // the span wrapper is added by default
            $(this).find('div.tablesorter-header-inner').addClass('roundedCorners');
        },

        // *** FUNCTIONALITY ***
        // prevent text selection in header
        cancelSelection: true,

        // other options: "ddmmyyyy" & "yyyymmdd"
        dateFormat: "mmddyyyy",

        // The key used to select more than one column for multi-column
        // sorting.
        sortMultiSortKey: "shiftKey",

        // key used to remove sorting on a column
        sortResetKey: 'ctrlKey',

        // false for German "1.234.567,89" or French "1 234 567,89"
        usNumberFormat: true,

        // If true, parsing of all table cell data will be delayed
        // until the user initializes a sort
        delayInit: false,

        // if true, server-side sorting should be performed because
        // client-side sorting will be disabled, but the ui and events
        // will still be used.
        serverSideSorting: false,

        // *** SORT OPTIONS ***
        // These are detected by default,
        // but you can change or disable them
        // these can also be set using data-attributes or class names
        headers: {
            // set "sorter : false" (no quotes) to disable the column
            0: {
                sorter: false
            },
            1: {
                sorter: "text"
            },
            2: {
                sorter: "digit"
            },
            3: {
                sorter: "digit"
            },
            4: {
                sorter: "digit"
            },
            5: {
                sorter: "digit"
            },
            6: {
                sorter: "digit"
            }
        },

        // ignore case while sorting
        ignoreCase: true,

        // forces the user to have this/these column(s) sorted first
        sortForce: null,
        // initial sort order of the columns, example sortList: [[0,0],[1,0]],
        // [[columnIndex, sortDirection], ... ]
        sortList: [
            [6, 1],
        ],
        // default sort that is added to the end of the users sort
        // selection.
        sortAppend: null,

        // starting sort direction "asc" or "desc"
        sortInitialOrder: "asc",

        // Replace equivalent character (accented characters) to allow
        // for alphanumeric sorting
        sortLocaleCompare: false,

        // third click on the header will reset column to default - unsorted
        sortReset: false,

        // restart sort to "sortInitialOrder" when clicking on previously
        // unsorted columns
        sortRestart: true,

        // sort empty cell to bottom, top, none, zero
        emptyTo: "bottom",

        // sort strings in numerical column as max, min, top, bottom, zero
        stringTo: "max",

        // extract text from the table - this is how is
        // it done by default
        textExtraction: {
            1: function (node) {
                return $(node).text();
            }
        },

        // use custom text sorter
        // function(a,b){ return a.sort(b); } // basic sort
        textSorter: null,

        // *** WIDGETS ***

        // apply widgets on tablesorter initialization
        initWidgets: true,

        // include zebra and any other widgets, options:
        // 'columns', 'filter', 'stickyHeaders' & 'resizable'
        // 'uitheme' is another widget, but requires loading
        // a different skin and a jQuery UI theme.
        widgets: ['numbering', 'zebra', 'columns'],

        widgetOptions: {

            // zebra widget: adding zebra striping, using content and
            // default styles - the ui css removes the background
            // from default even and odd class names included for this
            // demo to allow switching themes
            // [ "even", "odd" ]
            zebra: [
                "ui-widget-content even",
                "ui-state-default odd"],

            // uitheme widget: * Updated! in tablesorter v2.4 **
            // Instead of the array of icon class names, this option now
            // contains the name of the theme. Currently jQuery UI ("jui")
            // and Bootstrap ("bootstrap") themes are supported. To modify
            // the class names used, extend from the themes variable
            // look for the "$.extend($.tablesorter.themes.jui" code below
            uitheme: 'jui',

            // columns widget: change the default column class names
            // primary is the 1st column sorted, secondary is the 2nd, etc
            columns: [
                "primary",
                "secondary",
                "tertiary"],

            // columns widget: If true, the class names from the columns
            // option will also be added to the table tfoot.
            columns_tfoot: true,

            // columns widget: If true, the class names from the columns
            // option will also be added to the table thead.
            columns_thead: true,

            // filter widget: If there are child rows in the table (rows with
            // class name from "cssChildRow" option) and this option is true
            // and a match is found anywhere in the child row, then it will make
            // that row visible; default is false
            filter_childRows: false,

            // filter widget: If true, a filter will be added to the top of
            // each table column.
            filter_columnFilters: true,

            // filter widget: css class applied to the table row containing the
            // filters & the inputs within that row
            filter_cssFilter: "tablesorter-filter",

            // filter widget: Customize the filter widget by adding a select
            // dropdown with content, custom options or custom filter functions
            // see http://goo.gl/HQQLW for more details
            filter_functions: null,

            // filter widget: Set this option to true to hide the filter row
            // initially. The rows is revealed by hovering over the filter
            // row or giving any filter input/select focus.
            filter_hideFilters: false,

            // filter widget: Set this option to false to keep the searches
            // case sensitive
            filter_ignoreCase: true,

            // filter widget: jQuery selector string of an element used to
            // reset the filters.
            filter_reset: null,

            // Delay in milliseconds before the filter widget starts searching;
            // This option prevents searching for every character while typing
            // and should make searching large tables faster.
            filter_searchDelay: 300,

            // Set this option to true if filtering is performed on the server-side.
            filter_serversideFiltering: false,

            // filter widget: Set this option to true to use the filter to find
            // text from the start of the column. So typing in "a" will find
            // "albert" but not "frank", both have a's; default is false
            filter_startsWith: false,

            // filter widget: If true, ALL filter searches will only use parsed
            // data. To only use parsed data in specific columns, set this option
            // to false and add class name "filter-parsed" to the header
            filter_useParsedData: false,

            // Resizable widget: If this option is set to false, resized column
            // widths will not be saved. Previous saved values will be restored
            // on page reload
            resizable: true,

            // saveSort widget: If this option is set to false, new sorts will
            // not be saved. Any previous saved sort will be restored on page
            // reload.
            saveSort: true,

            // stickyHeaders widget: css class name applied to the sticky header
            stickyHeaders: "tablesorter-stickyHeader"

        },

        // *** CALLBACKS ***
        // function called after tablesorter has completed initialization
        initialized: function (table) {},

        // *** CSS CLASS NAMES ***
        tableClass: 'tablesorter',
        cssAsc: "tablesorter-headerSortUp",
        cssDesc: "tablesorter-headerSortDown",
        cssHeader: "tablesorter-header",
        cssHeaderRow: "tablesorter-headerRow",
        cssIcon: "tablesorter-icon",
        cssChildRow: "tablesorter-childRow",
        cssInfoBlock: "tablesorter-infoOnly",
        cssProcessing: "tablesorter-processing",

        // *** SELECTORS ***
        // jQuery selectors used to find the header cells.
        selectorHeaders: '> thead th, > thead td',

        // jQuery selector of content within selectorHeaders
        // that is clickable to trigger a sort.
        selectorSort: "th, td",

        // rows with this class name will be removed automatically
        // before updating the table cache - used by "update",
        // "addRows" and "appendCache"
        selectorRemove: "tr.remove-me",

        // *** DEBUGING ***
        // send messages to console
        debug: true

    });

    // Extend the themes to change any of the default class names ** NEW **
    $.extend($.tablesorter.themes.jui, {
        // change default jQuery uitheme icons - find the full list of icons
        // here: http://jqueryui.com/themeroller/ (hover over them for their name)
        table: 'ui-widget ui-widget-content ui-corner-all', // table classes
        header: 'ui-widget-header ui-corner-all ui-state-default', // header classes
        icons: 'ui-icon', // icon class added to the <i> in the header
        sortNone: 'ui-icon-carat-2-n-s',
        sortAsc: 'ui-icon-carat-1-n',
        sortDesc: 'ui-icon-carat-1-s',
        active: 'ui-state-active', // applied when column is sorted
        hover: 'ui-state-hover', // hover class
        filterRow: '',
        even: 'ui-widget-content', // even row zebra striping
        odd: 'ui-state-default' // odd row zebra striping
    });
}
    </script>
  </head>
  <body>
    <div id="wrap">
    <table id="dataTable" class="tablesorter">
    <thead>
        <tr>
            <th>Position</th>
            <th>Trainer</th>
            <th>Battles</th>
            <th>Wins</th>
            <th>Losses</th>
            <th>Win Rate</th>
            <th>Rating</th>
        </tr>
    </thead>
    <tbody id="dataTableBody"></tbody>
</table>
    </div>
    <a id="regresar" href="http://www.pokeclub.net/forum">Regresar al Foro</a>
    <noscript>Parece que tu navegador no soporta JavaScript! Actívalo para poder visualizar está página ;)</noscript>
  </body>
</html>

............................................... ........................................

1 个答案:

答案 0 :(得分:1)

您的 jQuery 是v1.4.2,而您的 tableSorter 版本是2.05b而您的 CSS 有许多缺少的部分。如果您不需要使用这些版本,这是解决方案。

替换以下行

<link rel="stylesheet" type="text/css" href="http://dl.dropboxusercontent.com/s/799k8f76ukikxa8/style.css" />
<script type="text/javascript" src="http://dl.dropboxusercontent.com/s/5c8cuzcww0bjua4/jquery-latest.js"></script>
<script type="text/javascript" src="http://dl.dropboxusercontent.com/s/2gbxvhkskdsch5p/jquery.tablesorter.js"></script>

<强>与

<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.17.1/css/theme.blue.css">    
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.17.1/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.17.1/jquery.tablesorter.widgets.min.js"></script>

,这一次

theme: 'default',

<强>与

theme: 'blue',

刚刚从CDN指出了最新版本,并在评论中指出了主题名称。