Ottieni un elenco separato da virgola dei valori di prima cella per le righe con il nome della classe (usando jQuery)?

StackOverflow https://stackoverflow.com//questions/25046666

  •  21-12-2019
  •  | 
  •  

Domanda

Cercando di afferrare ID dalla tabella sottostante quando viene selezionata una riga.Ad esempio, la jQuery dovrebbe tornare: "12,14" .. Il mio codice qui sotto ritorna Stringa vuota?

My HTML:

<table id="display" width="100%">
  <thead>
      <tr>
           <th>ID</th>
           <th>first</th>
           <th>last</th>
           <th>number</th>
       </tr>
   </thead>
<tbody>
...etc...
   <tr class="selected">
      <td>12</td>
      <td>Bob</td>
      <td>Smith</td>
      <td>9999</td>
   </tr>
   <tr>
      <td>13</td>
      <td>Lee</td>
      <td>Smith</td>
      <td>8888</td>
   </tr>
   <tr class="selected">
      <td>14</td>
      <td>JJ</td>
      <td>Wolf</td>
      <td>77777</td>
   </tr>
... etc..
</table>
.

La mia jQuery:

 var nameIDs = $('table tr.selected td:first').map(function () {
                return this.value;
            }).get().join(',');
.

È stato utile?

Soluzione

Il value non è definito per TD, è necessario utilizzare this.innerText o this.innerHTML, utilizzare anche first-child anziché first

demo live

var nameIDs = $('table tr.selected td:first-child').map(function () {
    return this.innerText;
}).get().join(',');
.

Modifica

L'HTML è anche non valido, hai perso la chiusura </td> in Second td per tutte le righe.

cambia

<td>Smith<td>
.

a

<td>Smith</td>
.

Altri suggerimenti

Questo codice potrebbe aiutarti

var elems = $(".selected>td:first-child");
for(var key in elems )
  elems[key] = $(elems[key]).html();
var values = elems.join(",");
.

Il risultato è nella stringa values

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top