Sum using jQuery each function without global variable

后端 未结 5 748
执念已碎
执念已碎 2021-01-14 03:47

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 +=          


        
5条回答
  •  星月不相逢
    2021-01-14 04:40

    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.

提交回复
热议问题