简体   繁体   English

除第一个元素外,所有具有类的元素的值之和

[英]Sum values from all elements with class, except for first

I'm using a bootstrap table to display a bunch of data and would like to sum up a column after the data has been loaded with JSON. 我正在使用引导程序表来显示一堆数据,并想在用JSON加载数据后总结一列。 I'd like to do the summing with Javascript so that the values will update when I apply filters to the table (See the filter extension here for an example http://wenzhixin.net.cn/p/bootstrap-table/docs/extensions.html . I'm currently trying to do this with the jQuery each() function by selecting a class that has been applied to every cell in a column, getting the value from each element and summing it into a variable. 我想用Javascript求和,以便在将过滤器应用于表时更新值(有关示例,请参见此处的过滤器扩展http://wenzhixin.net.cn/p/bootstrap-table/docs/ extensions.html我目前正在尝试使用jQuery each()函数,方法是选择一个应用于列中每个单元格的类,从每个元素中获取值并将其求和为变量。

Has anyone done this before with bootstrap tables? 有人用引导表做到过吗?

Here is what I currently have (This is returning NaN in the end): 这是我目前所拥有的(最终将返回NaN):

function sum_revenue() {

    var sum = 0;

    // remove class from column header because it does not contain numbers
    $('.revenue').first().removeClass('revenue');

    $('.revenue').each(function(){

        sum += parseInt($(this).val());

    });

    console.log(sum);

}

This works -- 这有效-

var sum = 0;

    // remove class from column header because it does not contain numbers
    $('.revenue').first().removeClass('revenue');


    $('.revenue').each(function(){
        sum += parseFloat($(this).text()); 
    });

    console.log("$" + sum);

You have an issue with execution order. 您对执行顺序有疑问。 JS will run those two block simultaneously. JS将同时运行这两个块。 You can do this synchronously as follows: 您可以按照以下步骤同步进行操作:

var sum = 0;
$('.revenue').each(function(index, value) {
    //Remove the first "header element from sum
    if(index !== 0) {
        sum += parseInt($(this).html(), 10);
    }
    //Remove the class if you still need to
    else {
        $(this).removeClass('revenue');
    }
});

console.log(sum);

Here is a fiddle: http://jsfiddle.net/a14rva0m/2/ 这是一个小提琴: http : //jsfiddle.net/a14rva0m/2/

Or you could do this with some crazy callback magic. 或者,您可以使用一些疯狂的回调魔术来做到这一点。

You can use .not to filter out the first element: 您可以使用.not过滤掉第一个元素:

var sum = 0;

$('.revenue').not(':first').each(function(){
    sum += parseInt($(this).val());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM