简体   繁体   English

Javascript全局变量在jQuery Droppable中不起作用

[英]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? 我想知道为什么myvar在那个地方myvar定义? Shouldn't it be accessible from any place? 不应该从任何地方访问?

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

Assign it directly to window to rule out scope conflicts. 将其直接分配给window以排除范围冲突。 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. 在预期范围之外创建var foo不会自动使其成为“全局”,只是对该范围块和嵌套范围是全局的。

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. 你正在为你的脚本创建全局 - 而不是nessecarily全局所有脚本。 Create it in window or document . windowdocument创建它。

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

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