开发者

Cannot control content added dynamically with .load

开发者 https://www.devze.com 2023-03-17 05:09 出处:网络
I have content that I\'m loading using an AJAX call and displaying the HTML (consisting of divs, etc) inside of a ul parent.

I have content that I'm loading using an AJAX call and displaying the HTML (consisting of divs, etc) inside of a ul parent.

Now I've written a series of .click and .hover fun开发者_运维百科ctions that work perfectly on everything, right up to where my content is dynamically loaded, and then don't work at all on the dynamically-loaded content.

I've gone through all my div ids to make sure they are correct and they are. Is there a way to gain control over the AJAX-loaded material?


The problem is that your code run only with the elements that existed at that time and no the "future" elements. You have 2 choices:

1) Re-run your "onload" javascript code (that was applied on document ready) after you load your ajax content.

2) Use .live() instead of .bind(): So change

$('#selector').bind('click', function(){..

To

$('#selector').live('click',function(){..

The difference is that live uses the elements that match the selector now and in the future, versus bind uses the elements that match the selector only at the time it's called.

Hope this helps. Cheers


Your event handlers are bound to elements that exist at the time that they are set.

Either re-attach the handlers to the new, dynamically-created material, or make use of live or delegate; these "attach a handler to the event for all elements which match the current selector, now and in the future".


You should either rebind the events after the content is loaded or use

.delegate (api) to have the event attached automatically to newly loaded elements.

something like:

$("ul#container").delegate("li", "hover", function(){
    doStuff();
});
$("ul#container").delegate("li", "click", function(){
    doOtherStuff();
});


Change

$('a#whatever').click(function(){....

To

$('a#whatever').live('click',function(){....
0

精彩评论

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