我有两个表,每个表都有唯一的ID例如:
<table id="cvo">
<tr id="1">
<td>C</td>
</tr>
<tr id="2">
<td>C</td>
</tr>
<tr id="3">
<td>O</td>
</tr>
<tr id="4">
<td>V</td>
</tr>
<tr id="5">
<td>C</td>
</tr>
</table>
<table id="prices">
<tr id="1">
<td>
<input type="text" class="editbox " value="0.30" />
</td>
</tr>
<tr id="2">
<td>
<input type="text" class="editbox " value="1.90" />
</td>
</tr>
<tr id="3">
<td>
<input type="text" class="editbox " value="4.40" />
</td>
</tr>
<tr id="4">
<td>
<input type="text" class="editbox " value="9.40" />
</td>
</tr>
<tr id="5">
<td>
<input type="text" class="editbox " value="0.95" />
</td>
</tr>
</table>
&#13;
我希望JS根据值(C V或O)总结价格表中的值
所以在上面的例子中,JS会返回: C:3.15 V:9.40 O:4.40。
我用.find()
尝试了以下内容var sum = 0.0;
$('#prices > tbody > tr').each(function() {
var price = $(this).closest('tr').find('.editbox').val();
var amount = Number(price)
sum+=amount;
});
console.log(sum)
答案 0 :(得分:1)
试试这个
function GetPriceValues()
{
var tableCvo = $('#cvo');
var tablePrices = $('#prices');
var trs = tableCvo.find('tr');
var prices = {};
$.each(trs, function(i, tr){
var oTr = $(tr);
var trid = oTr.attr('id');
var text = oTr.text();
var price = tablePrices.find('#'+trid+' .editbox').val();
var priceObj = prices[text];
if(!priceObj){
prices[text] = Number(price);
}else{
prices[text] = prices[text]+Number(price);
}
});
var keys = Object.keys(prices);
$.each(keys, function(i, key){
console.log(key+":"+prices[key]);
});
}
答案 1 :(得分:1)
var sum = {};
var prices = $("#prices input")
$("#cvo td").each(function(index){ // for each letter
if(!sum.hasOwnProperty($(this).text())){ // create sum of the letter if not created
sum[$(this).text()]=0;
}
sum[$(this).text()]+=Number($(prices.get(index)).val()); // add the price related to the current index
})
console.log(sum)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="cvo">
<tr id="1">
<td>C</td>
</tr>
<tr id="2">
<td>C</td>
</tr>
<tr id="3">
<td>O</td>
</tr>
<tr id="4">
<td>V</td>
</tr>
<tr id="5">
<td>C</td>
</tr>
</table>
<table id="prices">
<tr id="1">
<td>
<input type="text" class="editbox " value="0.30" />
</td>
</tr>
<tr id="2">
<td>
<input type="text" class="editbox " value="1.90" />
</td>
</tr>
<tr id="3">
<td>
<input type="text" class="editbox " value="4.40" />
</td>
</tr>
<tr id="4">
<td>
<input type="text" class="editbox " value="9.40" />
</td>
</tr>
<tr id="5">
<td>
<input type="text" class="editbox " value="0.95" />
</td>
</tr>
</table>
答案 2 :(得分:0)
var sum = {};
$('.editbox').each(function() {
var id = $(this).closest('tr').attr('data-id');
code = $('#' + id).text(); //ignore TD and just return text inside
if (!sum[code]) { sum[code] = 0; }
sum[code] += parseFloat($(this).val());
});
var result = '', i;
for (i in sum) {
result += i + ':' + sum[i] + ' ';
}
您在第二个表中使用重复的ID,它应该与第一个表匹配:
<table id="prices">
<tr data-id="1">
仅在理论上有效,没有测试,对不起。