开发者

Javascript variable scoping issue

I'm having a problem referencing a global variable inside an object literal:

开发者_运维知识库function f() {
    globalVar = "test";
}

$(document).ready(function() {
    f();
    var a = $("#id").autocomplete({ 
        lookup: globalVar //says globalVar is undefined
    });
    $("#button").click(function() {
        alert(globalVar); //works
    });
});

How can I set the value of lookup to globalVar?


you can define it outside all functions like this;

var globalVar ;

function f() {
    globalVar = "test";
}

$(document).ready(function() {
    f();
    alert(globalVar); //works
    var a = $("#id").autocomplete({ 
        lookup: globalVar 
    });
});


There is no reason that shouldn't work, it either has to do with a misunderstanding on how to use that autocomplete function, or a problem in the function itself. But the global should be assigned, and there is no problem assigning a global to an object that way. Either way, without more code (i.e. that autocomplete function), can't say what the issue is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜