求和表格单元格
<table>
<tr>
<td><input type="text"></td>
<td><input class="price" type="text" value="100"></td>
<td><input class="quantity" type="text" value="2"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input class="price" type="text" value="100"></td>
<td><input class="quantity" type="text" value="5"></td>
<td><input type="text"></td>
</tr>
<tfoot>
<tr class="summary">
<td>Total:</td>
<td id="total_price"></td>
<td id="total_quantity"></td>
<td class="second"></td>
<td class="third"></td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function() {
var sum = 0;
var quantity = 0;
$('.price').each(function() {
sum += (parseInt($('.price').val()) * parseInt($('.price').val()));
quantity += parseInt($('.quantity').val();
});
$('#total_price').html(sum);
$('#total_quantity').html(quantity);
})
</script>
输出必须为:总和:700;总数量:7
答案 0 :(得分:7)
将$('.price')
更改为$(this)
,以引用回调中的元素。
$(document).ready(function() {
var sum = 0;
var quantity = 0;
$('.price').each(function() {
var price = $(this);
var q = price.closest('tr').find('.quantity').val();
sum += parseInt(price.val()) * parseInt(q);
quantity += parseInt(q);
});
$('#total_price').html(sum);
$('#total_quantity').html(quantity);
});
答案 1 :(得分:1)
在$(this)
中使用$.each()
,
$('.price').each(function() {
sum += (parseInt($(this).val())*parseInt($(this).val()));
quantity += parseInt($this.closest('tr').find('.quantity').val();
});
答案 2 :(得分:1)
您的代码存在语法错误。
<script type="text/javascript">
$(document).ready(function(){
var sum = 0;
var quantity = 0;
$('.price').each(function() {
sum += (parseInt($('.price').val(), 10)*parseInt($('.price').val(), 10));
quantity += parseInt($('.quantity').val(), 10);
});
$('#total_price').html(sum);
$('#total_quantity').html(quantity);
})
</script>
答案 3 :(得分:1)
尝试使用每种方法的索引,
var sum = 0;
var quantity = 0;
$('.price').each(function(i){
sum += $('.price')[i].value * $('.quantity')[i].value;
quantity += $('.quantity')[i].value * 1;
});
$('#total_price').html(sum);
$('#total_quantity').html(quantity);
此处Fiddle
答案 4 :(得分:1)
纠正你jquery:
var sum = 0;
var quantity = 0;
$('.price').each(function (i) {
sum += $('.price')[i].value * $('.quantity')[i].value;
quantity += $('.quantity')[i].value * 1;
});
$('#total_price').html(sum);
$('#total_quantity').html(quantity);
FIDDLE: http://jsfiddle.net/ekzWJ/1/
答案 5 :(得分:1)
我使用父类概念来获取数量值。现在它的工作找到尝试。
$(document).ready(function(){
var sum = 0;
var quantity = 0;
var singleProduct,singleQuantity;
$('.price').each(function() {
singleProduct = parseInt($(this).val());
console.log(singleProduct);
singleQuantity = parseInt($(this).parent().parent().find('.quantity').val());
sum = sum+(singleProduct*singleQuantity);
quantity = quantity+singleQuantity;
});
console.log(sum+"-"+quantity);
$('#total_price').html(sum);
$('#total_quantity').html(quantity);
});