Javascript 变量作用域问题
我在引用对象文字内的全局变量时遇到问题:
function f() {
globalVar = "test";
}
$(document).ready(function() {
f();
var a = $("#id").autocomplete({
lookup: globalVar //says globalVar is undefined
});
$("#button").click(function() {
alert(globalVar); //works
});
});
如何将 lookup
的值设置为 globalVar?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样在所有函数之外定义它;
you can define it outside all functions like this;
没有理由不工作,它要么与如何使用自动完成功能的误解有关,要么与功能本身的问题有关。但是全局应该被分配,并且以这种方式将全局分配给对象是没有问题的。无论哪种方式,如果没有更多代码(即自动完成功能),都无法说出问题是什么。
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.