access head javascript variable in .js file jquery function
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.
You need to surround the JavaScript code in the head
with script
tags.
Therefore, your first example should really be:
<head>
<script>
var overlayAlignment = ["left:20px","right:40px","left:50px"];
</script>
</head>
And your second should be:
<head>
<script>
setOverlayAlignment("value1", "value2", "values3");
</script>
</head>
Weird just tried this and it worked. Strange I thought window.onload and $(document).ready were the same thing.
window.onload = function () {
$(document).ready(function () {
alert(overlayAlignment[0]);
});
}
Apparently overlayAlignment was not ready when $(document).ready was called but it will be available after window.onload.
精彩评论