Domanda

Voglio estrarre i dati da una tabella HTML come

<table>
    <tr>
        <th> Header1 </th>
        <th> Header2 </th>
        <th> Header3 </th>
    </tr>
    <tr>
        <td> Value 1,1 </td>
        <td> Value 2,1 </td>
        <td> Value 3,1 </td>
    </tr>

    ... rows ...

</table>

e ottenere gli array:

  • un allineamento per le intestazioni
  • una matrice 2D per i valori di colonna (o una matrice per ogni colonna)

    Come posso fare questo usando jQuery?

    Non mi importa di serializzare, o metterlo in un oggetto JSON perché voglio usarlo per eseguire il rendering di un grafico.


    correlata domanda di progettazione generale:

    Al momento ho qualcosa di simile

    1. ajax query returns html table
    2. use jQuery to get values from html table
    3. render chart
    

    lo fa più senso per gettare un oggetto JSON indietro dalla query Ajax e quindi rendere una tabella e un grafico da lì?

        
  • È stato utile?

    Soluzione

    come questo ?

    $(function() {
    
      var headers = $("span",$("#tblVersions")).map(function() { 
        return this.innerHTML;
      }).get();
    
      var rows = $("tbody tr",$("#tblVersions")).map(function() { 
        return [$("td:eq(0) input:checkbox:checked",this).map(function() { 
          return this.innerHTML;     
        }).get()];
      }).get();
    
      alert(rows);
    });
    

    Altri suggerimenti

    http://jsfiddle.net/ish1301/cnsnk/

    var header = Array();
    
    $("table tr th").each(function(i, v){
            header[i] = $(this).text();
    })
    
    alert(header);
    
    var data = Array();
    
    $("table tr").each(function(i, v){
        data[i] = Array();
        $(this).children('td').each(function(ii, vv){
            data[i][ii] = $(this).text();
        }); 
    })
    
    alert(data);
    

    Un altro modo di farlo

    var headers = jQuery('th').map(function(i,e) { return e.innerHTML;}).get();
    var datas = []
    jQuery.each(jQuery('tr:gt(0)'), function(i,e ) {
       datas.push(jQuery('td', e).map(function(i,e) {
                                         return e.innerHTML; 
                                      }).get()
                 );
    });
    

    Qualcosa sulla falsariga di:

    var thArray = new Array();
    var contentArray = new Array();
    
    $('th').each(function(index) {
      thArray[index] =    $(this).html();
    })
    
    
    $('tr').each(function(indexParent) {
      contentArray['row'+indexParent] = new Array();
        $(this).children().each(function(indexChild) {
          contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
        });
    });
    

    Questo ti dà due matrici, thArray che è un array di intestazioni e contentArray che è una matrice 2D che contiene righe e colonne: ritorna contentArray['row1']['col0'] "Value 1,1"

    In realtà, contentArray contiene del th così ... con riferimenti a 'row0'

      

    lo fa più senso per gettare un oggetto JSON indietro dalla query Ajax e quindi rendere una tabella e un grafico da lì?

    Sì, assolutamente. Ritorno JSON in risposta alla vostra richiesta AJAX, allora si può rendere la tabella utilizzando qualcosa come jQuery Templates e utilizzare gli stessi dati per generare il grafico pure.

    sto armeggiare con la stessa cosa qui, ma io preferisco l'iterazione attraverso tutte le tabelle e scrivere gli array di intestazione e il corpo in proprietà di ogni tavolo, quindi ecco la mia modifica alla risposta originale:

    $(function() {
    $("table").each(function(){
      var $table = $(this),
          $headerCells = $("thead th", $(this)),
          $rows = $("tbody tr", $(this));
      var headers = [],
          rows = [];
    
    
    $headerCells.each(function(k,v) {
       headers[headers.length] = $(this).text();
      $table.prop("headAry", headers);
    });
    
    $rows.each(function(row,v) {
      $(this).find("td").each(function(cell,v) {
        if (typeof rows[cell] === 'undefined') rows[cell] = [];
        rows[cell][row] = $(this).text();
        $table.prop("bodAry", rows);
      });
    });
    console.log($(this).prop('headAry'));
    console.log($(this).prop('bodAry'));  
    });
    });
    

    JSbin

    I penserebbe che sarebbe più sensato per ottenere un array di JSON ritorno dalla chiamata AJAX e generare la vostra tabella / grafico da questo. Con i modelli di jQuery questo non è difficile a tutti.

    Ecco una modifica della risposta di Girolamo Wagner che usi ricorsive mappe invece di una mappa all'interno di una 'ogni':

    http://jsbin.com/oveva3/383/edit

      var headers = $("th",$("#meme")).map(function() { 
        return this.innerHTML;
      }).get();
    
      var rows = $("tbody tr",$("#meme")).map(function() { 
        return [$("td",this).map(function() { 
          return this.innerHTML;     
        }).get()];
      }).get();
    
    Autorizzato sotto: CC-BY-SA insieme a attribuzione
    Non affiliato a StackOverflow
    scroll top