简体   繁体   中英

Javascript global variable doesn't work in jQuery Droppable

This must be some exception as I'm pretty sure it should work:

var myvar; // global variable

function draggableinit(e, ui){
    console.log(myvar); // still defined here
    jQuery('.drop-div').droppable({
        deactivate: function(event, ui){
            console.log(myvar); // why undefined?
        }
    });
}

function set(){
    var myvar = jQuery('.cont').resizable({
        start: function(event, ui) {  },
        resize: function(event, ui) {  },
        stop: function(event, ui) { // functions to manipulate size  }
    });
    return myvar;
}

jQuery(document).ready(function(){
    myvar = set();
    jQuery('.some-div').draggable({
        "start": draggableinit
    });
});

I'm wondering why myvar is undefined in that place? Shouldn't it be accessible from any place?

Documentation: http://jqueryui.com/draggable/

Assign it directly to window to rule out scope conflicts. That should work. Creating var foo outside of an intended scope doesn't automatically make it "global", just global to that scope block and nested scopes.

function draggableinit(e, ui){
    jQuery('.drop-div').droppable({
        deactivate: function(event, ui){
            console.log(window.myvar); // why undefined?
        }
    });
}

jQuery(document).ready(function(){
    window.myvar = 123;
    jQuery('.some-div').draggable({
        "start": draggableinit
    });
});

You are making it global for your script - not nessecarily global for all script. Create it in window or document .

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