javascript - 如何获取函数外部变量的值?

标签 javascript jquery

我有这个函数,我需要在函数之外获取变量 $overall 的值,我该怎么做?

$(function(){
     function ca($tr_value, $qty ){
     window.$overall = 0;

    $($tr_value).each(function() {

        var $qnt = $(this).find($qty);
        var $price = $(this).find("td").eq(2);

        var sum = parseFloat($price.text()) * parseFloat($qnt.val());

        $(this).find("td").eq(3).text(sum);
        $(this).find(".priceitem").attr('value', $(this).find("td").eq(2).text());
        $(this).find(".totalitem").attr('value', sum);

        $overall += sum;

        return window.overall;

    });

    $("#total").text($overall);
    $(".total").attr('value', $overall);
}

    function ca_transp(){
    var $overall_transp = 0;

    $("tr.sum_transp").each(function() {

        var $qnt = $(this).find(".qty_transp");
        var $price = $(this).find("td").eq(2);

        var sum = parseFloat($price.text()) * parseFloat($qnt.val());

        $(this).find("td").eq(3).text(sum);
        $(this).find(".priceitem").attr('value', $(this).find("td").eq(2).text());
        $(this).find(".totalitem").attr('value', sum);

        $overall_transp += sum;

    });

    $("#total_transp").text($overall_transp);
    $(".total").attr('value', $overall_transp);

}

//]]>  

   function suma_total(){
    var $suma_total = 0;    

    $("tr.total").each(function() {

        //var $qnt = $(this).find(".total");

        var $total_parcial = $(this).find("td").eq(1);
        var sum = parseFloat($total_parcial.text());


        $(this).find("td").eq(1).text(sum);
        $suma_total += sum;


    });





    $("#total_cotizacion").text($suma_total);
    $(".total_cotizacion").attr('value', $suma_total);

}
    ca_transp();
    $('input.qty_transp').bind('change keyup',function(){ca_transp();});
    ca("tr.sum", ".qty");
    $('input.qty').bind('change keyup',function(){ca("tr.sum", ".qty");});
    alert($overall);

});

感谢您的帮助。

最佳答案

在函数外部定义它,但这将使其成为全局的。

$(function(){
    var $overall;
    function ca($tr_value, $qty ){
       $overall = 0;
       $($tr_value).each(function() {

P.S 您还嵌套了 document.ready 函数。你不需要这样做。事实上你的代码可以被清理很多。我认为您不需要创建全局 $overall 变量。您的代码目前结构不正确,如果您明确了您的意图,那么我可以修改它。

关于javascript - 如何获取函数外部变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10755448/

相关文章:

javascript - 如何创建一个以对象为元素的唯一数组?

javascript - 弹出时为对话框添加自定义动画

php - 提交此表单时如何向用户隐藏 URL?

java - 是否有一个 javascript 库可以在图像上进行注释并将注释作为图像保存在服务器中?

jquery - jQuery 元素是插件的实例吗?

javascript - Flot:系列是选项中意外的标识符

javascript - 使 JS 函数更高效和动态

javascript - 单击时将输入值添加到 html 属性

javascript - 如何使日期成为父值?

javascript - 单击按钮时使字段可编辑