Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用元素计算';jQuery中的内容_Javascript_Jquery - Fatal编程技术网

Javascript 使用元素计算';jQuery中的内容

Javascript 使用元素计算';jQuery中的内容,javascript,jquery,Javascript,Jquery,我想使用相关元素的文本(mcost_el=mcount_el*mprice_el)运行计算,并将结果写入另一个元素的文本(到“mcost_el”) 但它不起作用。可能是类似于 elements = $("body").children().length 看一看,像这样的东西: $('tr').each(function(){ var count=parseFloat($('.mcount_el',this).text().replace(",",".")); var price=p

我想使用相关元素的文本(
mcost_el=mcount_el*mprice_el
)运行计算,并将结果写入另一个元素的文本(到“mcost_el”)


但它不起作用。

可能是类似于

elements = $("body").children().length
看一看,像这样的东西:

$('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);
});
实例:


不同之处在于,不是对字符串执行
parseInt
,而是对结果int执行
parseFloat
,而是对字符串执行
parseFloat

您需要这样的操作-

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);
});
哪个会-

  • 循环遍历每个表行
  • 对于当前表行,按查找计数和价格变量 使用
    $(this.find('td')
    语法从与当前行相关的
    中提取它们
  • 将两个变量相乘,并将结果加到总数中

工作演示-

您还可以在children函数中为更具体的子元素添加一个过滤器。是的,我只是不明白他到底想计数什么
mcount\u el
包含元素的计数
mprice\u el
包含价格
mcost_el
包含计算成本。是的,现在我又读了一遍,标题与问题不匹配:)是否有必要用小数替换逗号?我认为JavaScript自动处理了这种本地化。(当然,我自己从来没有处理过。)在您的示例中,不要在每个结果中使用mcost_el identity=(@mblase75-我尝试过,但没有替换结果更改。看起来javascript不会将
视为小数位(至少在我的机器上)我对问题进行了编辑,以反映我理解您的问题,如果此编辑不正确,请回滚。无需
parseFloat
两次。count不是整数(3,9)在第二行。
parseFloat
不会将
视为十进制分隔符。请参阅:我假设这将作为一个本地化问题自动处理,只要本地用户的国家将其视为十进制分隔符。我自己从未处理过此类问题,因此如果我错了,请按照Jamiec的做法添加一个
。替换(“,”,“)
$("#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));
});
$('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);
});
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);
});