简体   繁体   中英

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?

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. 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

2- Access the value on the HTML using javascript/jQuery.

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

(Example in jQuery for simplicity)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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