简体   繁体   English

如何从函数外部访问局部变量?

[英]How to access to local variable from outside the function?

How to access to local variable from outside the function ? 如何从函数外部访问局部变量?

When pressed, it should alert distance_bottom value, but it's not working, how can I make it work? 当按下时,它应该警告distance_bottom值,但是它不起作用,如何使它起作用?

http://jsfiddle.net/dyjb8r9w/11/ http://jsfiddle.net/dyjb8r9w/11/

<script>
$(window).load(function(){
(function() {    
    var mY, distance_bottom,
        $distance_bottom = $('#distance_bottom span'),
        $element_bottom  = $('#element_bottom');

    function calculatedistance_bottom(elem , mouseY) {
        return Math.floor(Math.sqrt(Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
    }

    $(document).mousemove(function(e) {        
        mY = e.pageY;
        distance_bottom = calculatedistance_bottom($element_bottom , mY);
        $distance_bottom.text(distance_bottom);
    });
})();
});
</script>





<script>
function reply_click()
{    
    alert(distance_bottom);
}
</script> 

You can make it global by prefixing it with window. 您可以通过在window.前面添加前缀来使其具有全局性window. and removing it from the variable declaration at the top. 并将其从顶部的变量声明中删除。 The below line did the trick 下面的线起到了作用

window.distance_bottom = calculatedistance_bottom($element_bottom , mY);

DEMO 演示

The way I see it you have two options, first one implies changing the function and the other one doesn't: 从我的角度来看,您有两个选择,第一个选择意味着更改功能,而另一个则没有:

1- make that a global variable by not declaring it inside the function with var 1-通过不使用var在函数中声明全局变量来使其成为全局变量

2- Access the value on the HTML using javascript/jQuery. 2-使用javascript / jQuery访问HTML上的值。

Ex: alert($('#distance_bottom span').html()); 例如:alert($('#distance_bottom span')。html());

(Example in jQuery for simplicity) (为简单起见,在jQuery中使用示例)

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

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