2009-12-11 13 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> 

Próbowałem z następnym kodem, aby uzyskać wartość i ilość każdego elementu.Jak iterować wiersze tabeli z JQuery i uzyskać dostęp do niektórych wartości komórek?

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

To nie działa. Czy ktoś może mi pomóc?

+2

co konkretnie nie działa dla Ciebie? –

Odpowiedz

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

Aby nie powtarzać wszystkich tabel na stronie, lepiej zastąpić $ ("tr.item"). Każdy (...) z $ ("# myTableId> tbody> tr.item"). Każdy (...) – thedrs

+7

Co robi '$ this = $ (this)'? – qed

+3

@qed przechowuje bieżącą wartość kontekstową "this" w zmiennej o nazwie $ this. Jeśli miałbyś zagnieździć kolejne wywołanie iteracyjne po przydzieleniu ilości, wywołanie "$ (this)" nie byłoby już tym samym wynikiem. Uważam, że Brian używa standardowej najlepszej praktyki, aby uniknąć tego zamieszania, ale mógł równie dobrze nazwać to "curRow", itp. – JWiley

16

to zrobić:

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

spróbować

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(); 
     } 
    }); 
    } 
} 
Powiązane problemy