【问题标题】:Updating jQuery Tablesorter plugin after removing a row from DOM从 DOM 中删除一行后更新 jQuery Tablesorter 插件
【发布时间】:2010-12-26 14:28:47
【问题描述】:

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

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

当前代码只是简单的小部件更新

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

无论如何要从寻呼机插件和tablesorter插件的缓存中删除“行”,以便当我“更新”表以反映行已被删除的事实时,它们不会重新出现通过缓存起死回生!

【问题讨论】:

    标签: jquery tablesorter pager


    【解决方案1】:

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

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

    把它放在你编辑表格的地方之后。

    【讨论】:

    • 谢谢。一件事 - usersTable.get(0).config.sortList 已经是一个数组。您不需要将其包裹在[ ] 中,否则 sorton 触发器将不起作用。
    【解决方案2】:

    在对这个问题进行了一些修改后,我得出了 jQuery Tablesorter + jQuery TablesorterPager 的组合使用 出现 问题。没有寻呼机删除行并执行“更新”就足够了。

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

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

    tablesorter 是一个 jQuery 插件 用 THEAD 和 TBODY 标签放入一个可排序的 没有页面刷新的表格。

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

    所以实际的解决方案是......开始寻找另一个 jQuery “Table” 插件,该插件从一开始就具有可以修改表格的意图/可能性。并且默认情况下支持此功能(删除,添加,....)


    好的,但这里是解决方案:

    jQuery Tablesorter + TablesorterPager 删除行(TR)

    javascript源代码的快速复制粘贴(基于TablesorterPager example的HTML)

    // "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

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

    【讨论】:

    • 嘿,我一直在试图让它在 Firefox 中工作,但到目前为止还没有运气。有什么想法吗?
    • 在我的演示页面重新声明现有变量时出现小错误。更新了答案中的链接和来源。在准备好的函数中检查源代码末尾的 // CHANGED HERE OOPS 更改评论
    • 为我工作 var index = $("tr", table).index(tr)-1;而不是 var index = $("tr", table).index(tr)-2;正常吗?
    • 重写方法Array.prototype.remove有必要吗?
    【解决方案3】:

    当您同时使用 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 = [];
    

    就是这样……

    来自波兰的问候 :)

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

            请查看 Motties tablesorter fork。他做了一个在使用 tablesorter 和 pager 插件时添加/删除行的示例。 http://mottie.github.com/tablesorter/docs/example-pager.html

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-01-15
              • 2011-03-19
              • 2011-09-21
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多