Can any anyone tell me why the example below doesn’t work:
var obj = $('#example');
function examplefunc(){
obj.hide();
}
Whilst the second one works fine:
function examplefunc(){
var obj = $('#example');
obj.hide();
}
I know that the difference is obvious – in first example we have global variable, whilst in second we have local one. But yet another example shows that global string var i accessible inside the function:
var text = "Hello World!"
function examplefunc(){
alert(text);
}
How can I make a global jQuery object variable visible inside the function in the first example? Is there any limitation of creating and using a global jQuery object? Any solutions?
I would hazard my guess that you’re executing this line of code:
Before the element with ID of
exampleis parsed into the DOM by the browser. You can work around it by moving your<script>element to below the#exampleelement in your document, or you can make use of the document ready event: