2015-09-27 73 views
1

我想从外部js文件获得一些配置,所以它似乎我需要做一个$(document).ready(function(){....内。保存配置对象的变量需要全局访问所有函数。所有功能没有任何理由在文档就绪功能中。jquery JavaScript的负载变量范围

从我看过的内容来看,以下内容应该是全球可用的app.config,但它不会!

window.app = {}; 

$(document).ready(function(){ 
    app.config = window[$('body').attr('data-app')]; 
}); 

console.log(app.config); 

这产生了错误app.config is undefined。我假设变量可以在文档中全局访问,但我需要它在全球各地都可用。我将如何做到这一点?如果可能的话,对文档准备就绪范围的解释将不胜感激!

回答

0

直到您为其指定值后才可用。直到ready事件触发为止,您不会为其指定值,但您立即查看该值(此时它仍为undefined)。

对于比较:

window.app = {}; 

$('button').on('click', function(){ 
    app.config = 1 
}); 

console.log(app.config); 

一个按钮被点击,直到这不设置config1

原理相同。

0

执行的实际顺序是这样的:

1. app = {} 
2. create listener 
3. console.log app.conig 
4. document is ready 
5. app.config is initalized 

你叫console.log(app.config)太早,对于app.config包含什么。

更好的方式来使用的配置它的初始化后的代码如下:

$(document).ready(function(){ 
    app.config = window[$('body').attr('data-app')] 

    # you should use config only after it's initialized 
    useConfig() 
    # call other functions here too 
}) 

function useConfig() { 
    console.log(app.config) 
} 
+0

显示这样的执行顺序是有帮助的,并解释了为什么我得到这个问题,但不解释它如何解决。脚本中有很多功能依赖于配置数据,但在文档就绪功能中查看所有内容似乎是错误的。有更好的解决方案吗? – Ally

+0

@Ally看到我的更新回答如何更好地完成 – dimakura

+0

好,所以任何需要配置数据的函数都必须在'document.ready'函数中调用,以使变量可用。但是如果'document.ready'函数之外的另一个函数调用需要配置数据的函数之一呢?那么变量是否可用?可能不会。现在我把所有的函数放在'document.ready'中,这样它就可以工作,但它似乎并不是正确的方式。 – Ally

-1

它确实全局可用。 $('body')。attr('data-app')的值可能是未定义的。 尝试,例如:

window.app = {}; 

$(document).ready(function(){ 
    app.config = window['Attr']; 
}); 

console.log(app.config); 
+0

该值定义为正常,如果从文档就绪功能内输出日志 – Ally

0

$(document).ready(function(){});会后

document.onreadystatechange= function() { 
    if (document.readyState == "complete") { 

    } 
}.//This is one ways of implementing $(document).ready(); 

解雇你的情况,你的console.log()获取调用的readyState评估完成之前。