I us开发者_开发技巧e jQuery 1.4.4 and would like to know if I can use .live() for Ajax events like ajaxStart / ajaxComplete. I have bound these events with .bind() and it works until now
jQuery(sourceId).bind("ajaxSend", function(event, xhr, ajaxOptions) {
// do something
});
equivalent
jQuery(sourceId).ajaxSend(function(event, xhr, ajaxOptions) {
// do something
});
A binding with .live() would be better for my use cases. Is it possible at all? I have read somewhere that the following snippet is not working
jQuery(sourceId).live("ajaxSend", function(event, xhr, ajaxOptions) {
// do something
});
Thanks in advance for your replies.
You can't do this with live(), although you might be able to do it with a custom event.
The implication with live() is that you are adding elements dynamically. The dynamically loaded elements must be done as the result of some event or AJAX callback so on the callback event set the new event binding there.
callback event...
//code thatadds the new elements...
jQuery('selector that identifies the new elements').bind("ajaxSend", function(event, xhr, ajaxOptions) {
// do something
});
You might want to wrap your code in a function.
Look at the comments here, copied from http://api.jquery.com/live/
The .live() technique is useful, but due to its special approach cannot be simply substituted for .bind() in all cases. Specific differences include:
DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector, as in the example above.
To stop further handlers from executing after one bound using .live(), the handler must return false. Calling .stopPropagation() will not accomplish this.
In jQuery 1.3.x only the following JavaScript events (in addition to custom events) could be bound with .live(): click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup.
As of jQuery 1.4 the .live() method supports custom events as well as all JavaScript events that bubble.
As of jQuery 1.4.1 even focus and blur work with live (mapping to the more appropriate, bubbling, events focusin and focusout).
As of jQuery 1.4.1 the hover event can be specified (mapping to mouseenter and mouseleave, which, in turn, are mapped to mouseover and mouseout).
No its not possible to use live instead of bind...
精彩评论