开发者

Allow jQuery to interface with elements called with .load()?

Before i tried loading the content via the .load() jquery function, i had an overlay which had v开发者_C百科arious elements which were targeted with events, such as a close button and some tabs, which worked great! I decided to keep my markup clean to load the overlay content with the .load() function which also works great, except the events that were tied with the elements which get pulled with the ajax don't work anymore.

Does anybody have an idea? :)


You need to use live binding on the buttons/close element.

Instead of use

$('a.close').click(function() { ... });

You need to use

$('a.close').live('click', function() { ... });

http://api.jquery.com/live/

This method is a variation on the basic .bind() method for attaching event handlers to elements. When .bind() is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call.


It sounds like the elements to which you are binding event handlers do not exist in the DOM at the point at which you bind the handlers and are loaded after via AJAX. Perhaps the easiest way to rectify this would be to bind the event handlers after load()? Or even use event delegation ( using .live() uses event delegation )


.live() seems to be the best practice but you also have the alternative of rebinding everything using the .load() callback, this will give you some flexibility shall you need it. Something like:

function LeBinding() {
    $('.clickable').click(function() { ... })
}

$('#container').load(url, data, function() {
    LeBinding();
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜