访问$(document)之外的变量.ready()& jQuery的 [英] accessing variable outside of $(document).ready() & jquery

查看:121
本文介绍了访问$(document)之外的变量.ready()& jQuery的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

so I have a .js file that is included into my html

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

If I put this inside my .js file,

$(document).ready(function(){    
      var siteRoot = $('.site-root').val();
      alert(siteRoot);
});

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

the code would alert the value properly, but if I do this:

var siteRoot = $('.site-root').val();
$(document).ready(function(){
      alert(siteRoot);
});

它会警告未定义

有一种方法可以在 $(document).ready()中访问变量,因为如果我将变量放在$ code $(document) .ready()它不会从其他js文件访问

is there a way to have something that's in $(document).ready() access variables outside it since if I put the variable inside $(document).ready() it wouldn't be accessible from other js files

推荐答案

你可以做它是全局的:

// 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);
});

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

Or even better, use some kind of namespace, like this:

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

$(document).ready(function(){
  alert(MyData.siteRoot);
});

这篇关于访问$(document)之外的变量.ready()& jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆