为什么这个jQuery对象未定义?

时间:2011-05-12 06:32:09

标签: jquery html

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

这两个对象都存在于我运行$的页面上。有人可以告诉我为什么我得到了异常mainimagepanel未定义

Firebug或Chrome开发工具中导致的异常。所以有人可以告诉我原因以及我如何检查两者都存在输入控件。

2 个答案:

答案 0 :(得分:6)

您的变量在匿名函数内声明,这就是它们的作用域。它们不存在于该功能之外。要修复它,您可以执行以下操作:

var mainimagepanel, postimagepanel;

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

然而,限制变量通常是一个很好的建议,以便它们存在于最严格的范围内。

答案 1 :(得分:2)

这是我的猜测。我会尝试比其他答案更深入一些。你有这个:

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

// ... bunch of code ...

mainimagepanel.show(); // oh no!

你刚刚遇到了一个名为范围的东西。具体来说,你遇到了一个叫做功能范围的东西。

让我们进行几个实验。

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.

希望这会让事情更加清晰。这一切的长短都是,你想要这样做:

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

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

// ... instead of here! ...