如何从javascript函数中获取变量值

How to get a variable value from a javascript function

本文关键字:获取 变量值 函数 javascript      更新时间:2023-09-26

我正试图从javascript函数中获得一个变量,但我遇到了一个问题,即在函数之外获取变量值。变量值可以很好地在函数内部输出。这里是脚本,但我怎么能得到状态的值,并在函数外使用它?

       <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

'return status;'是在事件函数中,而不是在get_id函数中。

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

$('.addressClick').click(function() {
    $('.statusSelected').removeClass('statusSelected');
    $(this).addClass('statusSelected');
});
alert($('.statusSelected').attr('id'));
$("#"+variable).confirm();