Hello people here is my code below...

你好,这里的人是我的代码......

var total = 0;
var find_total;
 function total_val(find_total){

$(find_total).each(function() {
    total += parseInt($(this).text());
    return total;
});

  }

Iam calling this function...

我叫这个功能......

$('#total_price').val(total_val('.price'));

#total_price and .price keeps changing for different div ids and class ... return total; does not work, any ways to fix this??

#total_price和.price不断更改不同的div id和class ... return total;不起作用,任何解决方法?

2 个解决方案

#1


1

You are returning the total value inside the .each() function, it would not return anything while we expecting a value from the function total_val(),

你在.each()函数中返回总值,当我们期望函数total_val()的值时,它不会返回任何内容,

Try,

function total_val(find_total){ 
   var total = 0; //remove the global variable total and use this.
   $(find_total).each(function() {
    total += parseInt($(this).text());
   });
   return total;
}

or you could use .reduce() to make your code simple.

或者您可以使用.reduce()来简化代码。

function total_val(find_total){ 
   return $(find_total).map(function() {
   return parseInt($(this).text());
   }).get().reduce(function(a,b){
   return a+b;
   });
}

Even simpler,

function total_val(find_total){ 
   return $(find_total).get().reduce(function(a,b){
      return a+ parseInt($(b).text(),10);
   },0);
}

更多相关文章

  1. 我无法理解为什么我的代码中的单击选择文本
  2. js字符串与html代码互相转换时怪想法:自己解析js字符串成普通字
  3. 解决FCKEditor编辑器在浏览器返回时显示html源代码的问题
  4. 如何让这段插入的innerHTML 里动态赋予的函数跑起来!
  5. 高分求:如何解析IdHTTP获得的http代码?用mshttp的IHTMLDocument2可
  6. 韩顺平_轻松搞定网页设计(html+css+javascript)_第19讲_js运行原
  7. jQuery animate()函数没有动画
  8. HTML显示日期时间代码 - [js 特效代码]
  9. 解决html代码中插入的图片在浏览器中不显示的办法

随机推荐

  1. android 开机自动运行程序
  2. android Activity活动周期 Service生命周
  3. 理解 Android(安卓)上的安全性
  4. 美化你的listView
  5. [转]Android异步处理系列文章索引
  6. NDK简单实例
  7. android 定制个性按钮 控件
  8. Head First Android(安卓)Development-笔
  9. Android(安卓)SVG图片解析Demo
  10. Android实现在列表List中显示半透明小窗