开发者

Calculate using elements' contents in jQuery

I want to run a calculation using the text of related elements (mcost_el=mcount_el*mprice_el) and write the result to the text of another element (to "mcost_el").

<tr>
 <td class="mcount_el">2</td>
 <td class="mprice_el">544,33</td>
 <td class="mcost_el">0</td>
</tr>
<tr>
 <td class="mcount_el">3,9</td>
 <td class="mprice_el">460,00</td>
 <td class="mcost_el">0</td>
</tr>

I write this code:

var count=0;
var price=0;
$('.mcost_el').each(function(){
      count=parseInt($('.mcount_el').each.text().replace(",","."));
      price=parseInt($('.mprice_el').each.text().replace(",","."));
      $('.mcost_el').开发者_StackOverflow中文版html(parseFloat(count)*parseFloat(price));
    });

but it don't work.


Something like this:

$('tr').each(function(){
   var count=parseFloat($('.mcount_el',this).text().replace(",","."));
   var price=parseFloat($('.mprice_el',this).text().replace(",","."));
   $('.mcost_el', this).html(count*price);
});

Live example: http://jsfiddle.net/BzVyc/

The difference is that, instead of doing a parseInt on the string then a parseFloat on the resulting int, you just do a parseFloat on the string.


You need something like this -

var count=0;
var price=0;
$('tr').each(function(){
      count=parseFloat($(this).find('td.mcount_el').text().replace(",","."));
  price=parseFloat($(this).find('td.mprice_el').text().replace(",","."));
      $(this).find('td.mcost_el').html(count*price);
});

Which will -

  • Loop through each table row
  • For the current table row, find the count and price variables by extracting them from the <td> relevant to the current row using $(this).find('td.<classname>') syntax
  • Multiply the two variables and and add the result to the total <td>

Working demo - http://jsfiddle.net/ipr101/AVGgU/1


maybe something along the line of

elements = $("body").children().length

have a look, length


$("#table_id tr").each(function() {
  var count = parseInt($(this).find(".mcount_el").text());
  var price = parseFloat($(this).find(".mprice_el").text());
  var cost = count * price;
  $(this).find(".mcost_el").text(cost.toFixed(2));
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜