javascript: can not use global variable in a function, to navigate the dom
beginner here... what am i missing?
i define a global variable that is a reference to an html element:
var x=document.getElementById("xxx1");
then, inside a function a try to reference that variable to navigate the dom:
x.innerHTML="dsfgfdgdf";
...doesn't work; if i define the variable inside the function it works, but i don't see how it's a scope problem... working with global variables insi开发者_如何转开发de functions works fine IF i don't use them in a dom context (object.property)
thanks
It's not a scope problem.
The most likely reason is that the element doesn't exist yet when you create the variable. You have to put the script element that creates the variable after the element that you want to access, as the code will run while the page is loading.
Another alternative is to declare the variable globally, and set it from the onload event that runs after the page has loaded:
<script>
var x;
function init() {
x = document.getElementById('xxx1');
}
</script>
<body onload="init();">
Is the getElementById executed before the DOM is loaded? (you should wait for domready or onload)
Is it possible that you overwrite the value in some other function?
I think the problem may be that if you declare that variable globally, when that line is evaluated the DOM is not totally loaded and therefore the element is not accessible.
When you declare it in the function, the variable will only be created when you call that function, when the DOM will mostly likely already be fully loaded.
Maybe your page is not fully loaded when you're calling getElementById.
Make sure you create the global variable x when the page has finished loading. Most libraries has a way to handle that, jQuery for example has the "ready"-function. If you dont want to use any libraries, you can always create the variable when the body-element calls the onload-event.
jQuery-style:
$(function(){
// create X here
})
body onload style:
<body onload="aFunctionThatCreatesYourVariable()">
精彩评论