我已經看過jQuery和添加列值的幾個例子;然而,這些例子只有一列和一個值。將特定列相加或相乘
我想知道你是否有多列,那麼你如何抓特定的?
例如,如果我想添加所有的數量列在一起或乘法費用列與其相鄰數量?
到目前爲止,我已經開始設置,但它不起作用。最初我試過
child_nodes.eq(2).text()
獲得數量的列,但我知道我的邏輯是關閉的。
$(document).ready(function() {
$('#checkout').on('click', function() {
item_count();
});
});
function item_count(){
$('.product').each(function() {
//find number of child nodes
var child_nodes = $(this).text(); //children returns all
var count = "";
for (var i=0; i<child_nodes.length; i++){
//whole row output
count += child_nodes.eq(i).text() + "\n";
}
});
//var total = parseInt($('.product').val());
var total += parseInt(count);
//update value
return $('#nitems').text(total);
};
我剛開始嘗試j查詢,所以我覺得我的代碼看起來很不喜歡,所以我模擬。
<h4>Shopping Cart</h4>
<table class='table'>
<thead>
<tr>
<th>Product</th><th>Unit cost</th><th>Quantity</th>
</tr>
</thead>
<tbody>
<tr class='product'>
<td>Milk Chocolate</td>
<td>7.48</td>
<td>5</td>
</tr>
<tr class='product'>
<td>Assorted Fine Chocolates</td>
<td>9.98</td>
<td>7</td>
</tr>
<tr class='product'>
<td>Assorted Milk & Dark Chocolates</td>
<td>12.98</td>
<td>9<td>
</tr>
<tr class='product'>
<td>Assorted Dessert Truffles</td>
<td>15.98</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>
<h3>Finalize Sale </h3>
<table class='table'>
<tr>
<td>Total Items</td>
<td><span id="nitems" >0</td>
</tr>
<tr>
<td>Subtotal</td>
<td><span id="subtotal" >0</td>
</tr>
<tr>
<td>5% Sales tax</td>
<td><span id="tax" >0</td>
</tr>
<tr>
<td>Total</td>
<td><span id="total" >0</td>
</tr>
<tr>
<td>Final amount (with 15% discount)</td>
<td><span id="final" >0</td>
</tr>
</table>
您能否提供比「不起作用」更多的細節?它是否給出錯誤?沒有給你想要的結果? – Scottie 2015-03-13 14:06:04
唯一的錯誤是我顯然缺少一個; ...從 'count + = child_nodes.eq(i).text()+「\ n」; } }); // var total = parseInt($('。product')。val()); var total + = parseInt(count);' – narue1992 2015-03-13 14:12:19
@Scottie除此之外,什麼都不打印 – narue1992 2015-03-13 14:12:57