开发者

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 gl开发者_如何学编程obal 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜