On Mon, 14 Sep 2009 11:15:53 +0100, ajp <[email protected]> wrote:
>
> I didn't expect this to work (with my 'compiler' hat on) but it does:
>
> var clickFunction = function() { $inner.doSomething() };
> $("div")
> .append("<div id=inner>bla</div>")
> .click(clickFunction);
>
> var $inner = $div.find("#inner");
>
> I was expecting an error for $inner to be undefined when the
> javascript parsed the first line, but the browser script engines seems
> quite happy with this sort of super-late declaration.
>
>
I guess that the clickFunction is executed when you actually click the
element. At that point the $inner variable is looked up in the local
scope. This is after the var has been initialised so the variable is
found...
It's similar to the problem you often see people have with code like:
for (var i=0; i<5; i++) {
$('item#' + i).click(
function()
{
alert(i);
}
);
}
People expect each item to alert it's own number but they will all alert 4
as that is the value of i by the time the click handler is actually
executed.
Hope that helps,
Kelvin :)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"jQuery Development" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/jquery-dev?hl=en
-~----------~----~----~----~------~----~------~--~---