I need to be able to access varA in more than one function, so it needs to be declared before the $(function() {});推荐答案问题是访问 varA 存在竞争条件:如果 $(function(){}); 在函数内部的代码之前运行,然后将不会对其进行定义.The issue is that there's a race condition for accessing varA: if the code below the $(function() {}); runs before the code inside the function, then it will not be defined.在这种情况下, $(document).ready()与 $()相同,因此 document 应该已经在函数内部做好准备.因此,您可以运行In this case, $(document).ready() is the same thing as $(), so the document should already be ready inside the function. Thus, you can just run$(function() { var varA; varA = 'varA has been altered!'; alert(varA); //displays 'varA has been altered!'});这不是作用域的问题:这是一个作用域相似的示例,但是竞争条件已删除,因此代码将起作用:This isn't an issue with scoping: here's an example where the scoping is similar, but the race condition is removed, so the code will work:$(function() { var varA; var def = $.Deferred(); def.then(function() { varA = 'varA has been altered!'; }).then(function() { alert(varA); //displays 'varA has been altered!' }); def.resolve();}); 这篇关于无法更新函数内部的全局变量并在函数外部调用它(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-22 13:07