从 DOM 中删除一行后更新 jQuery Tablesorter 插件

发布于 2024-08-14 11:49:51 字数 445 浏览 5 评论 0 原文

我目前有一些代码隐藏已删除的行,然后使用 .remove() 函数将其删除。

然而,我很难让它保持“删除”状态,因为每次我刷新表排序分页器插件或我正在使用的过滤器插件插件时..删除的行会重新出现,因为它们当然被缓存了。

目前的代码只是简单地更新小部件,

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

是否有办法从分页器插件和表排序器插件的缓存中删除“行”,以便当我“更新”表以反映行已被删除的事实时他们不会通过缓存复活!

I have some code at the moment that hides a row that is deleted and then removes it using the .remove() function.

However I'm having difficulty is making it remain "deleted" as every time I refresh the table sorted pager plugin or the filter plugin addon I'm using.. the deleted rows re-appear as they are of course cached.

Current code just simple with widget update at the moment

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

Is there anyway to remove the "row" from both the cache of the pager plugin and also the tablesorter plugin so that when I "update" the table to reflect the fact a row has been removed they don't re-appear back from the dead via the cache!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

挽袖吟 2024-08-21 11:49:51

我找到了一个适合我的解决方案:

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

将其放在编辑表格的位置之后。

I found a solution that worked for me:

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

Put this after the place where you've edited the table.

假扮的天使 2024-08-21 11:49:51

经过一番修改这个问题后,我得出结论,这些问题出现是由于 jQuery Tablesorter + jQuery TablesorterPager 的组合使用。如果没有寻呼机删除行并执行“更新”就足够了。

当您还包含寻呼机时,正确执行此操作会变得更加困难(正如您正确注意到存在一些缓存问题一样)。

但问题的主要原因是 jQuery Tablesorter 不被认为可用于您打算修改的表(在添加/删除行的意义上)。当您另外使用 TablesorterPager 时,这一点更适用。只需重读 jQuery Tablesorter 的描述即可

tablesorter 是一个 jQuery 插件
转换标准 HTML 表格
THEAD 和 TBODY 标记为可排序的
没有页面刷新的表。

TableSorter 清晰简洁的应用领域。它甚至没有在页面上提及 ajax、编辑、删除、附加……或类似术语。 它仅用于对静态表进行排序。

所以实际的解决方案是......开始寻找另一个 jQuery“表”插件,该插件从一开始就以表可以被构建的意图/可能性为基础。修改的。默认情况下支持此功能(删除、添加……)


不过,这里是解决方案:

jQuery Tablesorter + TablesorterPager 删除行(TR)

javascript 源代码的快速复制粘贴(基于 TablesorterPager 示例

// "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")}  );
});

我用我的解决方案为您制作了一个测试页(单击红色 TD 的 == 删除该行)。

http://jsbin.com/uburo (http://jsbin.com/uburo/edit 获取来源)

如果问题仍然在于如何/为什么/....评论

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
turning a standard HTML table with
THEAD and TBODY tags into a sortable
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

无语# 2024-08-21 11:49:51

当您同时使用 tablesorterpager 和 tablesorterfilter 插件时,事情会变得棘手 - 解决方案为:

$("#gridTable").trigger("update").trigger("appendCache").trigger("applyWidgets");

仅适用于寻呼机,过滤器有另一个缓存。我已经寻找解决方案近 2 小时,最后我写了这样的内容:

$("#deleteRowButton").click( function(){
  // index of row which will be deleted
  var index = $('#gridTable tr[rel="'+$("#removeThisID").val()+'"]').index();
  // table with tablesorter
  var table = document.getElementById( 'gridTable' ).config.cache.row;
  // deleting row
  $('#gridTable tr[rel="'+$("#removeThisID").val()+'"]').remove();
  // truly DELETING row, not only mark as deleted - after this list of rows should look like [tr], [tr], [tr], undefined, [tr], ...
  delete( table[index] );
  // tablesorter things
  $("#gridTable").trigger("update").trigger("appendCache").trigger("applyWidgets");
});

我正在删除 rel 属性与 input#removeThisID 值相同的行。

现在是时候修改 tablesorterfilter 插件了。在 doFilter 函数中,找到行:

// Walk through all of the table's rows and search.
// Rows which match the string will be pushed into the resultRows array.
var allRows = table.config.cache.row;
var resultRows = [];

并将其替换为:

// Walk through all of the table's rows and search.
// Rows which match the string will be pushed into the resultRows array.
var allRows = table.config.cache.row;

// refresh cache 'by hand'
var newcache = new Array();
var i = 0;        
for( var a in allRows )
{
  newcache[i] = allRows[a];
  i++;
}
allRows = newcache;
var resultRows = [];

就这样......

来自波兰的问候:)

Things goes tricky when you use both tablesorterpager and tablesorterfilter plugins - solution with:

$("#gridTable").trigger("update").trigger("appendCache").trigger("applyWidgets");

works only for pager, filter has another cache. I've looking for solution for almost 2 hours, at last i've written something like this:

$("#deleteRowButton").click( function(){
  // index of row which will be deleted
  var index = $('#gridTable tr[rel="'+$("#removeThisID").val()+'"]').index();
  // table with tablesorter
  var table = document.getElementById( 'gridTable' ).config.cache.row;
  // deleting row
  $('#gridTable tr[rel="'+$("#removeThisID").val()+'"]').remove();
  // truly DELETING row, not only mark as deleted - after this list of rows should look like [tr], [tr], [tr], undefined, [tr], ...
  delete( table[index] );
  // tablesorter things
  $("#gridTable").trigger("update").trigger("appendCache").trigger("applyWidgets");
});

I'm deleting row which has rel attribute the same as input#removeThisID value.

Now it's time to modify tablesorterfilter plugin. In doFilter function, find lines:

// Walk through all of the table's rows and search.
// Rows which match the string will be pushed into the resultRows array.
var allRows = table.config.cache.row;
var resultRows = [];

and replace these with:

// Walk through all of the table's rows and search.
// Rows which match the string will be pushed into the resultRows array.
var allRows = table.config.cache.row;

// refresh cache 'by hand'
var newcache = new Array();
var i = 0;        
for( var a in allRows )
{
  newcache[i] = allRows[a];
  i++;
}
allRows = newcache;
var resultRows = [];

that's all...

regards form Poland :)

微凉徒眸意 2024-08-21 11:49:51

这似乎是一种奇怪的方法,但实际上它对我有用。表格呈现良好,寻呼机工作正常。

$("#tabeBodyId").empty();
$("#tableId colgroup").remove();

//Update table(done using Ajax)
$("#tableId").tablesorter({widthFixed: true}).tablesorterPager({container: $("#pager")}); 

This seems an odd approach, but actually it worked for me. Table renders fine and pager works properly.

$("#tabeBodyId").empty();
$("#tableId colgroup").remove();

//Update table(done using Ajax)
$("#tableId").tablesorter({widthFixed: true}).tablesorterPager({container: $("#pager")}); 
未蓝澄海的烟 2024-08-21 11:49:51

尽管缺少一行更新(请参见下面的代码),但抖动解决方案几乎对我有用。我扩展了代码以允许在表中插入新的 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]);
}

您可以使用如下:

添加带有复杂 HTML 的新 TR :

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>

Jitter solution was almost working for me although a line was missing for update (see code below). I've extended the code to allow insert new TR's in table.

I've been playing around and it works for me under FFox, didn't check on IExplorer. Anyway there's a bug I couldn't fix yet: If you add a new TR and then you try to delete it it won't be deleted from table :(

// "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]);
}

And you can use is as follows:

Add new TR with complex HTML in it:

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"));

Remove any TR:

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

My simplified sample table:

<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>
饭团 2024-08-21 11:49:51

最好使用 table.splice(index, 1);比删除(表[索引]);! “删除”只是清空数组元素,但没有完全删除。对不起我的英语! =)

Better to use table.splice(index, 1); than delete( table[index] );! "Delete" do just empty element of array, but not deleted completely. Sorry for my English! =)

以为你会在 2024-08-21 11:49:51

请看看 Motties tablesorter fork。他制作了一个在使用表排序器和分页器插件时添加/删除行的示例。
http://mottie.github.com/tablesorter/docs/example-pager.html

Please have a look at Motties tablesorter fork. He made an example for adding/removing rows when using tablesorter and pager plugin.
http://mottie.github.com/tablesorter/docs/example-pager.html

一身骄傲 2024-08-21 11:49:51

老问题,但有时基本的解决方案最适合为旧代码提供快速修复。

因此,一个简单的选择是隐藏该行。

var rowId = 20;
var rowToDelete = $('.tablesorter').find('tr#' + rowId);
rowToDelete.attr('id','REMOVED');   //so your JS code will not find
rowToDelete.addClass('hide');       //so the row isn't re-displayed by the tablesorter plugin when a sort is performed after an update.
rowToDelete.remove();               //delete from HTML

Old Question, but sometimes a basic solution is best for providing a quick fix to old code.

So, an easy option is to just hide the row.

var rowId = 20;
var rowToDelete = $('.tablesorter').find('tr#' + rowId);
rowToDelete.attr('id','REMOVED');   //so your JS code will not find
rowToDelete.addClass('hide');       //so the row isn't re-displayed by the tablesorter plugin when a sort is performed after an update.
rowToDelete.remove();               //delete from HTML
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文