Miré preguntas similares anteriores y solo encontré una respuesta con el siguiente código dividiendo los datos en 2 tablas:
// ==UserScript== // @name TABLE SPLITTER // @namespace http://www.w3schools.com/ // @description DESCRIPTION!!! // @include http://www.w3schools.com/css/css_table.asp // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js // @require https://raw.github.com/tomgrohl/jQuery-plugins/master/jcookie/script/jquery.jcookie.min.js // @version 1 // ==/UserScript== $(function(){ // YOUR JAVASCRIPT CODE HERE // YOU HAVE JQUERY INCLUDED setTimeout(function(){ var mainTable = $("table"); var splitBy = 3; var rows = mainTable.find ( "tr" ).slice( splitBy ); var secondTable = $("<table id='secondTable' style='background:pink;'><tbody></tbody></table>").insertAfter("table"); secondTable.find("tbody").append(rows); console.log(secondTable); mainTable.find ( "tr" ).slice( splitBy ).remove(); }, 3000); });
Estoy buscando algo como esto que divida la información en tablas según la cantidad de opciones diferentes que tengo.
en última instancia, me gustaría algo como: Meta
O incluso mejor, elimine el tipo de la salida y haga que se muestre antes de cada una de las nuevas tablas como esta: opción 2
No estoy seguro de si eso es posible y me encantaría un poco de ayuda.
Esta no es la solución óptima, puedes hacerte una idea y mejorarla.
Lea los comentarios de JS.
var dynamicData = $('#dynamicData'); // To identify the parent that we will append data to. $(document).ready(function(){ $('.types').each(function(){ // loop on each type and check if that type not appended inside '#dynamicData' as 'h5', if no,t append it and append a table related to it var name = $.trim($(this).text()); var check = $('h5#i_' + name , dynamicData).length; if (check === 0){ $(dynamicData).append('<h5 id="i_' + name + '">' + name + '</h5>'); $(dynamicData).append('<table id="t_' + name + '" class="table table-hover table-striped table-bordered"></table>'); $('table#t_' + name).append('<thead>'+ '<tr>'+ '<th>Product</th>'+ '<th>Price</th>'+ '</tr>'+ '</thead>'+ '<tbody>'+ '</tbody>'); } }); $('#allContent > tr').each(function(){ // loop on each row in '#allContent' and read '.types' class, then clone this row and remove the type then append it inside the target table using id var name = $.trim($('.types',this).text()); $(this).clone().find('.types').remove().end().appendTo('table#t_' + name + ' > tbody'); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <h4 class="text-center text-danger">Before:</h4> <table class="table table-hover table-striped table-bordered"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Type</th> </tr> </thead> <tbody id="allContent"> <tr> <td>TV</td> <td>250$</td> <td class="types">Product</td> </tr> <tr> <td>Channel</td> <td>1$</td> <td class="types">Service</td> </tr> <tr> <td>Channel</td> <td>1$</td> <td class="types">Service</td> </tr> <tr> <td>DVD</td> <td>14$</td> <td class="types">Product</td> </tr> <tr> <td>Support</td> <td>15$</td> <td class="types">Team</td> </tr> </tbody> </table> <h4 class="text-center text-danger">After:</h4> <div id="dynamicData"></div>
Mi primer pensamiento es hacer una lista única de los tipos. Luego recorra esa lista, clonando la tabla original para cada uno. Luego recorra la tabla clonada y elimine todo lo que no desea allí. Definitivamente no es el más eficiente, pero es simple y funciona.
let types = [... new Set($('table.original tr td:last-of-type') .get().map(type => type.textContent))]; //create a container for the cloned tables $('table.original').after(`<h4>After:</h4><div class="cloned-tables"></div>`) //loop over types, clone tables, modify accordingly $.each(types, function(index, type) { $(`<p class="type">${type}</p>${$('table.original')[0].outerHTML}`) .appendTo('.cloned-tables') .find('tr td:last-of-type').each(function() { if (this.textContent !== type) { this.parentElement.remove(); } this.remove(); }); }); //remove all type header cells $(`.cloned-tables table th:last-of-type`).remove();
h4{color: red;} .type{color: blue;}
<h4>Before:</h4> <table class="original"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td>TV</td> <td>$250</td> <td>Product</td> </tr> <tr> <td>Channel</td> <td>$1</td> <td>Service</td> </tr> <tr> <td>Channel</td> <td>$1</td> <td>Service</td> </tr> <tr> <td>DVD</td> <td>$14</td> <td>Product</td> </tr> <tr> <td>Support</td> <td>$15</td> <td>Team</td> </tr> </tbody> </table> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Otro pensamiento sobre el uso de Greasemonkey, asegúrese de que la tabla exista y esté poblada antes de intentar hacer algo con ella. Greasemonkey está en un ámbito diferente al del código original, por lo que document.ready()
es inexacto. A veces, las cosas se cargan de forma muy asincrónica, lo que hará que el código válido parezca roto. Tiendo a hacer algo como esto:
let loading = setInterval(function() { if ($('table.original').length) { clearInterval(loading); //greasmonkey code here } }, 1000);