访问.js文件中的头javascript变量jquery函数
我的 dom 头部有一个 javascript 变量,我需要在外部 js 文件中访问它,但它似乎未定义。
我脑子里有类似的东西。
<head>
<script type="text/javascript">
var overlayAlignment = ["left:20px","right:40px","left:50px"];
</script>
</head>
外部 .js 文件
$(document).ready(function () {
alert(overlayAlignment[0]);
});
在我的外部 js 文件中,我想使用该变量,但类似的事情总是出现未定义,不知道我做错了什么。
我发现如果我将overlayAlignment 变量添加到.js 文件中,我可以从头部的外部.js 运行一个函数来设置overlayAlignment 变量。
<head>
<script type="text/javascript">
setOverlayAlignment("value1", "value2", "values3");
</script>
</head>
外部 .js 文件
function setOverlayAlignment(value1, value2, value3) {
overlayalignment[0] = value1;
overlayalignment[1] = value2;
overlayalignment[2] = value3;
}
但是,当我尝试在 jquery 函数中使用它时,它仍然显示为未定义。奇怪,我以为 $(document).ready 是告诉函数等待 dom 加载运行,如果是这样的话,为什么overlayAlignment 在运行时未定义?
我需要这样做,因为overlayAlignment 变量值仅在运行时才知道。
I have a javascript variable in the head of my dom and I need to access it in an external js file but it seems to come up undefined.
In my head I have something like.
<head>
<script type="text/javascript">
var overlayAlignment = ["left:20px","right:40px","left:50px"];
</script>
</head>
external .js file
$(document).ready(function () {
alert(overlayAlignment[0]);
});
In my external js file I want to use the variable but something like this comes up undefined all the time, any idea what I am doing wrong.
I found that I could run a function from the external .js in the head to set the overlayAlignment variable if I add the overlayAlignment variable to the .js file.
<head>
<script type="text/javascript">
setOverlayAlignment("value1", "value2", "values3");
</script>
</head>
external .js file
function setOverlayAlignment(value1, value2, value3) {
overlayalignment[0] = value1;
overlayalignment[1] = value2;
overlayalignment[2] = value3;
}
This still comes up as undefined when I try to use it in my jquery function however. Strange, I thought $(document).ready was to tell the function to wait till the dom is loaded to run, if that is the case why is overlayAlignment undefined when it runs?
I need to do it like this because the overlayAlignment variable values are only known at runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
script
标签将head
中的 JavaScript 代码括起来。因此,你的第一个例子应该是:
第二个例子应该是:
You need to surround the JavaScript code in the
head
withscript
tags.Therefore, your first example should really be:
And your second should be:
奇怪的是刚刚尝试了这个并且成功了。奇怪的是,我认为 window.onload 和 $(document).ready 是同一件事。
显然,当 $(document).ready 被调用时,overlayAlignment 还没有准备好,但在 window.onload 之后它将可用。
Weird just tried this and it worked. Strange I thought window.onload and $(document).ready were the same thing.
Apparently overlayAlignment was not ready when $(document).ready was called but it will be available after window.onload.