开发者

why this jQuery object undefined?

$(function () {
            var mainimagepanel = $("#blah1");
            v开发者_JAVA百科ar 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.


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.


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! ...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜