Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this jQuery object undefined?

Tags:

html

jquery

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

both object exist on the page where i run my $. can someone show me why i got exception mainimagepanel is not defined

the exception caused in Firebug or Chrome dev tool. so someone can tell me reason and how i can check that a input control exist on both.

like image 992
Anirudha Gupta Avatar asked Feb 25 '23 05:02

Anirudha Gupta


2 Answers

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

var mainimagepanel, postimagepanel;

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

It is however usually good advice to limit your variables so that they exist in the tightest possible scope.

like image 82
sje397 Avatar answered Feb 26 '23 20:02

sje397


Here's my guess. I'll try to go a bit further in depth than the other answers have. You have this:

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

// ... bunch of code ...

mainimagepanel.show(); // oh no!

You've just run into something called scoping. Specifically, you've run into something called function scope.

Let's run a couple of 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's 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.

Hopefully, that makes things clearer. The long and short of it all is, you want to do this instead:

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

    // ... put your code here ...
});

// ... instead of here! ...
like image 28
issa marie tseng Avatar answered Feb 26 '23 22:02

issa marie tseng