访问 $(document).ready() & 之外的变量jQuery
所以我有一个 .js 文件包含在我的 html 中
如果我把它放在我的 .js 文件中,
$(document).ready(function(){
var siteRoot = $('.site-root').val();
alert(siteRoot);
});
代码会正确地警告该值,但如果我这样做:
var siteRoot = $('.site-root').val();
$(document).ready(function(){
alert(siteRoot);
});
它会警告未定义,而不是
有没有办法拥有这样的东西在 $(document).ready()
中访问其外部的变量,因为如果我将变量放入 $(document).ready()
中,则其他变量将无法访问js 文件
so I have a .js file that is included into my html
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);
});
it would alert undefined instead
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将其设置为全局:
或者更好的是,使用某种名称空间,如下所示:
You can either make it a global:
Or even better, use some kind of namespace, like this:
执行此操作的最佳方法基本上是创建一个空的全局变量或创建一个命名空间来存储变量。然后在 document.ready 中只需将
$('.site-root').val()
添加到该变量即可。这样,您可以在知道 .site-root 存在并且在整个应用程序中全局可用后设置 siteRoot 变量。
The best way to do this is to basically create an empty global variable or create a namespace to store the variables. Then in the document.ready just add your
$('.site-root').val()
to that variable.That way you set the siteRoot variable after you know .site-root exists and it is available globally throughout the application.
变量可以在
$(document).ready(
)中使用,因为它是全局变量,但是您可能会得到undefined
,因为没有值在文档准备好之前可用于.siteRoot
,只需尝试以下操作:现在,如果您希望该变量可以全局使用并立即使用< /em> 在你的应用程序的其他部分,你必须重新设计您的解决方案,以便应用程序的其他部分也仅在 DOM 准备就绪时才使用它。
The variable is available from within
$(document).ready(
since it is a global, but you are probably gettingundefined
because no value is available for.siteRoot
before the document is ready. Just try this:Now, if you expect a value to be available for that variable globally and for immediate use in other parts of your application, you will have to re-work your solution such that other parts of your application also make use of it only when the DOM is ready.
然而,您可以通过执行以下操作来共享:
在您的应用程序中,您可以通过以下方式引用它:
您也可以延迟加载它:
HTH。
Yet you can share by doing something like this:
And throughout your app you could reference it via:
You could also lazy load it:
HTH.