访问$(document).ready()和jquery之外的变量

kam*_*lot 10 javascript jquery dom

所以我有一个包含在我的HTML中的.js文件

如果我把它放在我的.js文件中,

$(document).ready(function(){    
      var siteRoot = $('.site-root').val();
      alert(siteRoot);
});
Run Code Online (Sandbox Code Playgroud)

代码会正确地提醒值,但如果我这样做:

var siteRoot = $('.site-root').val();
$(document).ready(function(){
      alert(siteRoot);
});
Run Code Online (Sandbox Code Playgroud)

它会警告undefined而不是

有没有办法在$(document).ready()访问变量之外有一些东西,因为如果我把变量放在$(document).ready()其中就不能从其他js文件访问

Pab*_*dez 18

您可以将其设为全局:

// this is the same as your example, 
// just wanted to stress that it's a part of the window (global) object
window.siteRoot = $('.site-root').val();
$(document).ready(function(){
      alert(window.siteRoot);
});
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,使用某种命名空间,如下所示:

var MyData = {};
MyData.siteRoot = $('.site-root').val();

$(document).ready(function(){
  alert(MyData.siteRoot);
});
Run Code Online (Sandbox Code Playgroud)