not mottie jquery tablesorter pager

jquery - not - tablesorter mottie



ActualizaciĆ³n del complemento jQuery Tablesorter despuĆ©s de eliminar una fila de DOM (7)

Tengo un código en el momento que oculta una fila que se elimina y luego la elimina con la función .remove ().

Sin embargo, tengo dificultades para hacer que permanezca "eliminado", ya que cada vez que actualizo el complemento de buscapersonas ordenado en la tabla o el complemento del complemento de filtro que estoy usando ... las filas eliminadas vuelven a aparecer ya que, por supuesto, se almacenan en caché.

Código actual simplemente simple con la actualización del widget en este momento

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

¿Hay alguna forma de eliminar la "fila" de la memoria caché del complemento de buscapersonas y también del complemento de la tabla de modo que cuando "actualizo" la tabla para reflejar el hecho de que se haya eliminado una fila, no vuelvan a aparecer de la muerto a través del caché!


Después de algunos retoques con este problema, concluyo que los problemas surgen del uso combinado de jQuery Tablesorter + jQuery TablesorterPager. Sin el buscapersonas, eliminar la fila y hacer y "actualizar" es suficiente.

Cuando también incluyes el buscapersonas, es mucho más difícil hacer esto correctamente (como has notado correctamente hay algunos problemas de almacenamiento en caché).

Pero la razón principal de su problema es que no se cree que jQuery Tablesorter se use para tablas que intenta modificar (en el sentido de agregar / eliminar filas). Y esto se aplica aún más cuando, además, utiliza TablesorterPager. Solo vuelve a leer la descripción de jQuery Tablesorter

tablesorter es un complemento de jQuery para convertir una tabla HTML estándar con las etiquetas THEAD y TBODY en una tabla clasificable sin actualizaciones de página.

Un campo de aplicación claro y conciso para TableSorter. Ni siquiera menciona ajax, editar, eliminar, agregar, ... o términos similares en la página. Es solo para ordenar una tabla estática.

Así que la solución real es ... comience a buscar otro complemento de "Tabla" de jQuery que se haya creado desde el principio con la intención / posibilidad de que la tabla pueda ser modificada. Y que soporta esto por defecto (eliminando, agregando, ....)

Ok, sin embargo, aquí está la solución para:

jQuery Tablesorter + TablesorterPager eliminar filas (TR)

Copia y pegado rápido del código fuente de javascript (HTML basado en el ejemplo de 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")} ); });

Hice una página de prueba para usted con mi solución (haga clic en el = = rojo TD eliminando esa fila).

http://jsbin.com/uburo ( http://jsbin.com/uburo/edit para la fuente)

Si la pregunta permanece sobre cómo / por qué / ... Comentario


Encontré una solución que me funcionó:

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

Coloca esto después del lugar donde has editado la tabla.


Es mejor usar table.splice (índice, 1); que eliminar (tabla [índice]) ;! "Eliminar" simplemente vacía el elemento de la matriz, pero no se elimina por completo. ¡Lo siento por mi ingles! =)


Esto parece un enfoque extraño, pero en realidad funcionó para mí. La tabla se procesa bien y el buscapersonas funciona correctamente.

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


La solución de Jitter casi estaba funcionando para mí, aunque faltaba una línea para la actualización (ver código a continuación). He extendido el código para permitir insertar nuevos TR en la tabla.

He estado jugando y me funciona con FFox, no revisé IExplorer. De todos modos, hay un error que aún no pude solucionar: si agrega una nueva TR y luego intenta eliminarla, no se eliminará de la tabla :(

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

Y puedes usarlo de la siguiente manera:

Añadir nuevo TR con HTML complejo en él:

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

Eliminar cualquier TR:

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

Mi tabla de muestra simplificada:

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


Las cosas se complican cuando usa los complementos tablesorterpager y tablesorterfilter. Solución con:

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

Funciona solo para buscapersonas, el filtro tiene otro caché. He buscado una solución durante casi 2 horas, por fin he escrito algo como esto:

$("#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"); });

Estoy eliminando la fila que tiene el atributo rel igual que el valor de entrada # removeThisID.

Ahora es el momento de modificar el plugin tablesorterfilter. En la función doFilter, encuentra líneas:

// 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 = [];

y reemplazarlos con:

// 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 = [];

eso es todo...

En cuanto a la forma de Polonia :)