Обновление jQuery плагин Tablesorter после удаления строки от DOM

У меня есть некоторый код в данный момент, который скрывает строку, которая удалена и затем удаляет его с помощью .remove () функция.

Однако я испытываю затруднения, заставляет его остаться "удаленным" как каждый раз, когда я обновляюсь, таблица отсортировала плагин пейджера или дополнение плагина фильтра, которое я использую.. удаленные строки вновь появляются, поскольку они, конечно, кэшируются.

Текущий код, просто простой с виджетом, обновляет в данный момент

$('.deleteMAP').live("click", function(){
  $(this).closest('tr').css('fast', function() {
 $(this).remove();
 $(".tablesorter").trigger("update");
 $(".tablesorter").trigger("applyWidgets");
  });
})

Должен туда так или иначе удалить "строку" и из кэша плагина пейджера и также из tablesorter плагина так, чтобы, когда я "обновляю" таблицу для отражения факта, строка была удалена, они не вновь появляются назад от мертвых через кэш!

19
задан Brian Tompsett - 汤莱恩 4 July 2015 в 13:28
поделиться

3 ответа

After some tinkering around with this problem I conclude the problems arise from the combined use of jQuery Tablesorter + jQuery TablesorterPager. With out the pager removing the row and doing and "update" is enough.

When you also include the pager it gets much more difficult to do this right (as how you noticed correctly there are some caching issues).

But the main reason for your problem is that jQuery Tablesorter isn't thought to be used for tables which you intent to modify (in the sense of adding/removing rows). And this applies even more when you additionally use TablesorterPager. Just reread the description of jQuery Tablesorter

tablesorter is a jQuery plugin for превращение стандартной таблицы HTML с Теги THEAD и TBODY в сортируемый table without page refreshes.

A clear and concise field of application for TableSorter. It doesn't even mention ajax, edit, remove, append, ..... or similar terms on the page. It is only for sorting a static table.

So the actual solution is.... start looking for another jQuery "Table" plugin which was built from the start with the intention/possibility that the table can be modified. And which supports this by default (removing, adding, ....)


Ok nonetheless here is the solution for:

jQuery Tablesorter + TablesorterPager remove rows (TR)

Quick copy-paste of the javascript source-code (HTML based on TablesorterPager example)

// "borrowed" from John Resig: Javascript Array Remove
// http://ejohn.org/blog/javascript-array-remove/
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

//repopulate table with data from rowCache
function repopulateTableBody(tbl) {
    //aka cleanTableBody from TableSorter code
    if($.browser.msie) {
        function empty() {
            while ( this.firstChild ) this.removeChild( this.firstChild );
        }
        empty.apply(tbl.tBodies[0]);
    } else {
        tbl.tBodies[0].innerHTML = "";
    }
    jQuery.each(tbl.config.rowsCopy, function() {
        tbl.tBodies[0].appendChild(this.get(0));
    });
}
//removes the passed in row and updates the tablesorter+pager
function remove(tr, table) {
    //pager modifies actual DOM table to have only #pagesize TR's
    //thus we need to repopulate from the cache first
    repopulateTableBody(table.get(0));
    var index = $("tr", table).index(tr)-2;
    var c = table.get(0).config;
    tr.remove();
    //remove row from cache too
    c.rowsCopy.remove(index);
    c.totalRows = c.rowsCopy.length;
    c.totalPages = Math.ceil(c.totalRows / config.size);
    //now update
    table.trigger("update");
    //simulate user switches page to get pager to update too
    index = c.page < c.totalPages-1;
    $(".next").trigger("click");
    if(index)
        $(".prev").trigger("click");
}

$(function() {
    var table;
    //make all students with Major Languages removable
    $('table td:contains("Languages")').css("background-color", "red").live("click", function() {
        remove($(this).parents('tr').eq(0), table);
    });

    //create tablesorter+pager
    // CHANGED HERE OOPS
    // var table = $("table#tablesorter");
    table = $("table#tablesorter");
    table.tablesorter( { sortList: [ [0,0], [2,1] ] } )
        .tablesorterPager( { container: $("#pager")}  );
});

I made a testpage for you with my solution (click the red TD's == removing that row).

http://jsbin.com/uburo (http://jsbin.com/uburo/edit for the source)

If question remain on how/why/.... Comment

5
ответ дан 30 November 2019 в 03:59
поделиться

Я нашел решение, которое мне помогло:

var usersTable = $(".tablesorter");
usersTable.trigger("update")
  .trigger("sorton", [usersTable.get(0).config.sortList])
  .trigger("appendCache")
  .trigger("applyWidgets");

Поставь это после того места, где ты редактировал таблицу.

17
ответ дан 30 November 2019 в 03:59
поделиться

Решение с джиттером почти работало для меня, хотя не хватало строки для обновления (см. код ниже). Я расширил код, чтобы позволить вставлять новые TR в таблицу.

Я поигрался, и это работает для меня под FFox, не проверял на IExplorer. В любом случае есть ошибка, которую я пока не смог исправить: Если вы добавите новый TR, а затем попытаетесь удалить его, он не будет удален из таблицы :(

// "borrowed" from John Resig: Javascript Array Remove
// http://ejohn.org/blog/javascript-array-remove/
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

//repopulate table with data from rowCache
function repopulateTableBody(tbl) {
    //aka cleanTableBody from TableSorter code
    if($.browser.msie) {
        function empty() {
            while ( this.firstChild ) this.removeChild( this.firstChild );
        }
        empty.apply(tbl.tBodies[0]);
    } else {
        tbl.tBodies[0].innerHTML = "";
    }
    jQuery.each(tbl.config.rowsCopy, function() {
        tbl.tBodies[0].appendChild(this.get(0));
    });
}
//removes the passed in row and updates the tablesorter+pager
function tablesorter_remove(tr, table) {
    //pager modifies actual DOM table to have only #pagesize TR's
    //thus we need to repopulate from the cache first
    repopulateTableBody(table.get(0));
    var index = $("tr", table).index(tr)-2;
    var c = table.get(0).config;
    tr.remove();

    //remove row from cache too
    c.rowsCopy.remove(index);
    c.totalRows = c.rowsCopy.length;
    c.totalPages = Math.ceil(c.totalRows / config.size);

    //now update
    table.trigger("update");
    table.trigger("appendCache");

    //simulate user switches page to get pager to update too
    index = c.page < c.totalPages-1;
    $(".next").trigger("click");
    if(index)
        $(".prev").trigger("click");
}

function tablesorter_add(tr, table) {
    //pager modifies actual DOM table to have only #pagesize TR's
    //thus we need to repopulate from the cache first
    repopulateTableBody(table.get(0));
    table.append(tr);

    //add row to cache too
    var c = table.get(0).config;
    c.totalRows = c.rowsCopy.length;
    c.totalPages = Math.ceil(c.totalRows / config.size);

    //now update
    table.trigger("update");
    table.trigger("appendCache");

    //simulate user switches page to get pager to update too
    index = c.page < c.totalPages-1;
    $(".next").trigger("click");
    if(index)
        $(".prev").trigger("click");

    //Set previous sorting method
    var sorting = c.sortList;
    if(sorting == '')
        sorting = [[0,0]];
    table.trigger("sorton", [sorting]);
}

И вы можете использовать это следующим образом:

Добавить новый TR со сложным HTML в нем:

tablesorter_add('<tr id="'+data.id+' " title="Haz click para editar" onclick="edit('+data.id+')"><td id="'+data.id+'_genus">'+data.genus+'</td><td id="'+data.id+'_species">'+data.species+'</td></tr>', $("#orchid_list"));

Удалить любой TR:

tablesorter_remove($("#"+orchid_id),$("#orchid_list"));

Мой упрощенный пример таблицы:

<table id="orchid_list" class="tablesorter">
<thead>
<tr>
    <th id="genus">Género</th>
    <th id="species">Especie</th>
</tr>
</thead>
<tbody>
    <tr id="2" title="Haz click para editar" onclick="edit('2')">
        <td id="2_genus">Amitostigma</td>

        <td id="2_species">capitatum</td>
    </tr>
    <tr id="4" title="Haz click para editar" onclick="edit('4')">
        <td id="4_genus">Amitostigma</td>
        <td id="4_species">tetralobum</td>
    </tr>
</tbody>
</table>
1
ответ дан 30 November 2019 в 03:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: