开发者

Jquery Event Handling Question

Say I have this code:

$(document).ready(function()
{
   $(".foo").click(processFooClick);
}

Once the document has loaded, then via javascript I dynamically add a new div with foo class to the document:

$("body").append( "<div class='foo'>click..</div>");

Would this new div also have the event handler automatically applied to it, or would I ne开发者_开发技巧ed to run the event setting code ( $(".foo").click(...) ) again?

Would using jquery's live function help with this? If so, how?


The new div will not have the event handler attached to it. live will allow it to work as you described:

$(".foo").live('click', processFooClick);

But, I'd just add the event handler to the new div again. You shouldn't use live unless you really don't control when new elements are added to the page.


click() is a shortcut for bind(). bind will attach directly to the matching elements. That means, no, your new element will not have a handler. Using $(".foo").live(processClick) will work, because live() works by attaching a handler to the document and catching bubbled-up events. Also look at delegate() for a more scoped live type of event handler.


When event handlers are added, they are added to the elements themselves, so adding new matching elements will not result in them having the event handlers. I believe you can re-assign the handlers.

Using .live() avoids this problem - I believe that (paraphrasing) events are handled on the fly, and if an element matches it it applied. You can add elements as needed and they will handle any events that have been applied to matching elements.


live would work, but your first method would not (if you add the div after the first click function was run)

If you decide to call click again, you need to make sure you are not adding the click handler twice to all your original foo divs, or they will be run twice


Your first method would not work, take a look at this jsFiddle: http://jsfiddle.net/esN4Q/

But, live would:

$(".foo").live('click', processFooClick);

jsFiddle Example of jQuery live: http://jsfiddle.net/ePmXU/ (I added an alert pop up in the jsFiddle so we can see if it works when it's clicked.)


I'd say you probably need to use live as your click event registration is done after DOMs are loaded. Any dynamically generated DOM won't get that event handler so you have to use live. In this case, something like:

$(".foo").live('click', processFooClick);

Or if you have a narrower context scope:

$(".foo", $(someContext)[0]).live('click', processFooClick);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜