Sum using jQuery each function without global variable

…衆ロ難τιáo~ 提交于 2019-12-01 07:06:23

问题


I want to add some HTML elements that have the same class name.

So, the code will be like this with jQuery.

$(".force").each(function (){
    a += parseInt( $(this).html());
});
$("#total_forces").html(a);

In this code, the variable has to be global.

Is there any other elegant way to sum every .force value and get the sum out of the each function without global variable?


回答1:


If you don't want to introduce a global variable, you could use something like this:

$("#total_forces").html(function() {
    var a = 0;
    $(".force").each(function() {
        a += parseInt($(this).html());
    });
    return a;
});



回答2:


For convenience, if you're going to be needing this same functionality frequently, I'd probably just make a plugin.

Example: https://jsfiddle.net/tzw4mkL2/

(function( $ ) {
    $.fn.sumHTML = function() {
       var sum = 0;
        this.each(function() {
           var num = parseInt( $(this).html(), 10 );
           sum += (num || 0);
        });
       return sum; 
    };
})( jQuery );

...which would be used like this:

$('#total_forces').html( $('.force').sumHTML() );

EDIT: Changed to guard agains NaN as noted by @Šime Vidas. Also ensured base-10 in the parseInt() and fixed a closing } that was missing.




回答3:


In short, no.

Why does a have to be global? It doesn't have to be global.

function aFunc() {
    var a = 0;

    $(".force").each(function (){
        a += parseInt( $(this).html());
    });

    return a;
}

$("#total_forces").html(aFunc());

Which, can be simplified to:

$("#total_forces").html(function() {
    var a = 0;

    $(".force").each(function (){
        a += parseInt( $(this).html());
    });

    return a;
});

Here a is local to aFunc, and is just one of millions of examples of it not being in the global scope.




回答4:


Don't want a global?

(function() {
    var a = 0;
    $('.force').each(function (){
        a += parseInt($(this).text());
    });
    $('#total_forces').text(a);
})();



回答5:


You can use $(".force").length, it returns the number of elements in the jQuery object.

jQuery API



来源:https://stackoverflow.com/questions/4377410/sum-using-jquery-each-function-without-global-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!