2009-12-11 4 views
41
<table class="checkout itemsOverview"> 
    <tr class="item"> 
     <td>GR-10 Senderos</td> 
     <td><span class="value">15.00</span> €</td> 
     <td><input type="text" value="1" maxlength="2" class="quantity" /></td> 
    </tr> 
    <tr class="item"> 
     <td>GR-10 Senderos<br/>GR-66 Camino de la Hermandad<br/>GR 88 Senderos del Jarama<br/>Camino del Cid</td> 
     <td><span class="value">45.00</span> €</td> 
     <td><input type="text" class="quantity" value="1" maxlength="2"/></td> 
    </tr> 
</table> 

Stavo provando con il codice successivo per ottenere il valore e la quantità di ogni articolo.Come eseguire iterazioni su una tabella di righe con JQuery e accedere ad alcuni valori di cella?

$("tr.item").each(function(i, tr) { 
    var value = $(tr + " span.value").html(); 
    var quantity = $(tr + " input.quantity").val(); 
}); 

Non funziona. Qualcuno può aiutarmi?

+2

ciò che in particolare non sta lavorando per voi? –

risposta

80
$("tr.item").each(function() { 
    $this = $(this); 
    var value = $this.find("span.value").html(); 
    var quantity = $this.find("input.quantity").val(); 
}); 
+14

Per non ripetere tutte le tabelle nella pagina, è meglio sostituire $ ("tr.item"). Ognuna (...) con $ ('# myTableId> tbody> tr.item'). (...) – thedrs

+7

Cosa fa '$ this = $ (this)'? – qed

+3

@qed memorizza il valore contestuale corrente di "questo" in una variabile denominata $ this. Se dovessi annidare un'altra chiamata iterativa dopo l'assegnazione della quantità, chiamare "$ (this)" non sarebbe più lo stesso risultato. Credo che Brian stia semplicemente usando le migliori pratiche standard per evitare questa confusione, ma avrebbe potuto chiamarlo con facilità "curRow", ecc. – JWiley

16

fare questo:

$("tr.item").each(function(i, tr) { 
    var value = $("span.value", tr).text(); 
    var quantity = $("input.quantity", tr).val(); 
}); 
0

provare questo

var value = iterate('tr.item span.value'); 
var quantity = iterate('tr.item span.quantity'); 

function iterate(selector) 
{ 
    var result = ''; 
    if ($(selector)) 
    { 
    $(selector).each(function() 
    { 
     if (result == '') 
     { 
     result = $(this).html(); 
     } 
     else 
     { 
     result = result + "," + $(this).html(); 
     } 
    }); 
    } 
} 
Problemi correlati