Why is this jQuery object undefined?

$(function () { var mainimagepanel = $("#blah1"); var postimagepanel = $("#blah2"); }); 

Both objects exist on the page where I run my $. can someone show me why i got the mainimagepanel exception undefined

exception thrown in Firebug or Chrome dev tool. so that someone can tell me the reason and how I can verify that the access control exists on both.

+4
source share
2 answers

Your variables are declared inside an anonymous function, and this is their scope. They do not exist outside this function. To fix this, you can do something like:

 var mainimagepanel, postimagepanel; $(function () { mainimagepanel = $("#blah1"); postimagepanel = $("#blah2"); }); 

However, as a rule, we advise you to limit your variables so that they exist in the maximum possible area.

+6
source

Here is my hunch. I will try to go deeper than the other answers. You have the following:

 $(function() { var mainimagepanel = $('#blah1'); var postimagepanel = $('#blah2'); }); // ... bunch of code ... mainimagepanel.show(); // oh no! 

You just came across what is called scoping . In particular, you are faced with what is called a function area .

Let me run some experiments.

 var a = 'hello'; var myfunc = function() { alert(a); var b = 'goodbye'; alert(b); }; alert(a); // pops 'hello'. good, we expected that. myfunc(); // pops 'hello', then 'goodbye'. good, that seems right too. alert(b); // error. because b was declared inside of myfunc, it doesn't exist out here. var myfunc2 = function() { a = 'greetings'; }; myfunc2(); alert(a); // pops 'greetings'. because myfunc2 is inside of our main code here, it can see the a out here. var myfunc3 = function() { var a = 'salutations'; alert(a); }; myfunc3(); // pops 'salutations'. that seems reasonable, that what we just set it to. alert(a); // pops 'greetings'. huh? turns out, because we var'd the a this time, it made a *new* a inside of myfunc3, and when you start talking about a, it assumes you want that one. 

Hope this makes things clearer. Long and short from all this, you want to do it instead:

 $(function() { var mainimagepanel = $('#blah1'); var postimagepanel = $('#blah2'); // ... put your code here ... }); // ... instead of here! ... 
+2
source

All Articles