开发者

reinitialize dom events after ajax calls

开发者 https://www.devze.com 2022-12-11 10:25 出处:网络
I have the following problem/doubt that I hope somebody could help me with. Let\'s say I have several javascript events being initialized when I load a page. In this page I allow the User to click on

I have the following problem/doubt that I hope somebody could help me with. Let's say I have several javascript events being initialized when I load a page. In this page I allow the User to click on several action buttons (which have those events). Now, one of these buttons makes in this case an ajax call in which a successful result will make that button disapear and make another button appear (I inject this html from the ajax response). In this moment I want to add as well an event to this new button, so after I inject the html I do so. When I click in this button I want the first button to appear again and this one to disapear. Now this new button (the one that was there in the beggining) has to have again that same event! Do I need to initialize again that event ? Is开发者_运维技巧n't there a way to make that autommaticaly somehow? I mean, if I have several events for all 's of a certain div, and I load with ajax another in that div, shouldn't that respond immediattly to the same events? Thanks


jQuery has a live event registering facility, that will keep events correct for all current and future matches for a selector. (jQuery.com)

As for plain Javascript, yes, you'll need to register the event again.


If you simply hide the original button (eg display:none ), then all the events you attached to it in the beginning will still be there.

New buttons that you create after the initial page load (eg, by adding them from an Ajax request) will need events to be attached to them when they are safely in the DOM.

jQuery has a feature for doing this automatically, which it calls live. This lets you specify a selector, and it will be constantly monitored. As soon as new objects appear in the DOM that match the original selector, the events will be attached to it as well.

Documentation for Live can be see here : http://docs.jquery.com/Events/live

0

精彩评论

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