简体   繁体   中英

jQuery global object doesn't work inside function

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:

var obj = $('#example');

Before the element with ID of example is parsed into the DOM by the browser. You can work around it by moving your <script> element to below the #example element in your document, or you can make use of the document ready event:

var obj;

$(function () {  // This function is run after the document is parsed and ready
    obj = $('#example');
});

function examplefunc(){
    obj.hide();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM