JQuery / Javascript: клиентская модификация вывода сетки данных asp.net, позволяющая работать табличному сортировщику - PullRequest
4 голосов
/ 31 марта 2009

Вывод таблицы данных asp.net не включает элементы thead и tbody, необходимые для работы jQuery TableSorter.

например. это выглядит так:

    <table>
        <tr>this is my header row</tr>
        <tr>content row 1</tr>
        <tr>content row 2</tr>
        <tr>content row 3</tr>
        ...
        <tr>content row n</tr>
    </table>

и должно выглядеть так:

    <table>
        <thead>
            <tr>this is my header row</tr>
        </thead>
        <tbody>
            <tr>content row 1</tr>
            <tr>content row 2</tr>
            <tr>content row 3</tr>
            ...
            <tr>content row n</tr>
        </tbody>
    </table>

Я включил следующий javascript для их динамической вставки, но таблица все еще не сортируется. Я подтвердил, что если я вручную вставлю теги thead и tbody непосредственно в выходной html, таблица будет сортируемой, но когда я пытаюсь сделать это с помощью DOM, она, похоже, не работает.

Чего мне не хватает?

    $(document).ready(function() 
        { 
            var tbl = document.getElementById('mytableid');

            // new header and body elements to be inserted
            var tblHead = document.createElement('thead');
            var tblBody = document.createElement('tbody');
            // get the first row and the remainder
            var headerRow = $(tbl).find('tr:first')
            var bodyRows  = $(tbl).find('tr:not(:first)');

            // remove the original rows
            headerRow.remove();
            bodyRows.remove();

            // add the rows to the header and body respectively
            $(tblHead).append(headerRow);
            $(tblBody).append(bodyRows);

            // add the head and body into the table
            $(tbl).append(tblHead);
            $(tbl).append(tblBody);

            // apply the tablesorter
            $(tbl).tablesorter(); 
        } 
    ); 

РЕДАКТИРОВАТЬ: Я на самом деле решил проблему, прежде чем опубликовать вопрос, но я подумал, что я все равно отправлю его, так как это может быть полезно для других ... Смотрите мой ответ ниже.

Ответы [ 2 ]

5 голосов
/ 31 марта 2009

Видимо, фантомный

элемент появляется в выходных данных. Хитрость заключается в том, чтобы убедиться, что он удален перед добавлением в сгенерированные ... Надеюсь, это кому-нибудь пригодится!
    $(document).ready(function() 
        { 
            var tbl = document.getElementById('mytableid');

            // new header and body elements to be inserted
            var tblHead = document.createElement('thead');
            var tblBody = document.createElement('tbody');
            // get the first row and the remainder
            var headerRow = $(tbl).find('tr:first')
            var bodyRows  = $(tbl).find('tr:not(:first)');

            // remove the original rows
            headerRow.remove();
            bodyRows.remove();

            // SOLUTION HERE: 
            // remove any existing thead/tbody elements
            $(tbl).find('tbody').remove();
            $(tbl).find('thead').remove();

            // add the rows to the header and body respectively
            $(tblHead).append(headerRow);
            $(tblBody).append(bodyRows);

            // add the head and body into the table
            $(tbl).append(tblHead);
            $(tbl).append(tblBody);

            // apply the tablesorter
            $(tbl).tablesorter(); 
        } 
    ); 
0 голосов
/ 02 ноября 2009

Приведенный выше код по-прежнему не обращается к ячейкам в заголовке. Чтобы преобразовать их из тегов в теги, вы можете добавить это:

$('thead tr td').each(function(i) { $(this).replaceWith("<th>" + $(this).html() + "<\/th>"); });

...