我使用jQuery 1.4.4并且想知道我是否可以使用.live()来执行Ajax事件,例如ajaxStart / ajaxComplete。我已经用.bind()绑定了这些事件,它一直有效,直到现在
jQuery(sourceId).bind("ajaxSend", function(event, xhr, ajaxOptions) {
// do something
});
equivalent
jQuery(sourceId).ajaxSend(function(event, xhr, ajaxOptions) {
// do something
});
与.live()的绑定对我的用例更好。有可能吗?我在某处读过以下代码片段无法正常工作
jQuery(sourceId).live("ajaxSend", function(event, xhr, ajaxOptions) {
// do something
});
提前感谢您的回复。
答案 0 :(得分:2)
虽然您可以使用自定义事件执行此操作,但您无法使用live()执行此操作。
live()的含义是您要动态添加元素。动态加载的元素必须作为某些事件或AJAX回调的结果完成,因此在回调事件中设置新的事件绑定。
callback event...
//code thatadds the new elements...
jQuery('selector that identifies the new elements').bind("ajaxSend", function(event, xhr, ajaxOptions) {
// do something
});
您可能希望将代码包装在函数中。
查看此处的评论,从http://api.jquery.com/live/
复制.live()技术很有用,但由于其特殊的方法,在所有情况下都不能简单地替换.bind()。具体差异包括:
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).
答案 1 :(得分:1)
不能使用live而不是bind ...