我无法理解 jQuery 变量范围。
var myVar;
function getMyVar() {
myVar = 'test';
}
$(window).load(function() {
getMyVar();
});
alert(myVar);
这段代码会提示“未定义”,我需要它来显示“测试”,我想在这里了解我的范围问题。
最佳答案
这不是范围问题。
alert
甚至在 window.load
事件被触发之前就开始执行,这是变量 myVar 被赋予值“test”的地方。
根据 MDN 文档:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
关于javascript - jQuery 变量作用域/调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6950289/