繁体   English   中英

如何从JavaScript函数获取变量值

[英]How to get a variable value from a javascript function

我正在尝试从javascript函数获取变量,但是在获取函数外部的变量值时遇到问题。 可以在函数内部很好地输出变量值。 这是脚本,但是如何获得status的值并在funcion之外使用它呢?

       <script>
            function get_id(){              
                $('.addressClick').click(function() {
                    var status = $(this).attr('id');
                    alert(status); // Here the value is printed correctly
                    return status;
                });
            }

            var variable = get_id();
            alert(variable);        // Here the valiable isn't outputed

            $("#"+variable).confirm();
    </script>

您不能这样做,请参阅我的示例:

function get_id(){              
    $('.addressClick').click(function() {
        //...
    });
    return 12;
}

var variable = get_id();
alert(variable); //12

“返回状态;” 在事件函数中,而不在get_id函数中。

解决方案是(如果您有大型项目,请不要使用全局变量):

$('.addressClick').click(function() {
    $('.statusSelected').removeClass('statusSelected');
    $(this).addClass('statusSelected');
});
alert($('.statusSelected').attr('id'));

$("#"+variable).confirm();

暂无
暂无

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

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