jquery:on vs live [英] jquery: on vs live

查看:67
本文介绍了jquery:on vs live的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么当我用 .on()替换 .live()时,我的事件不会通过 html()方法插入AJAX的响应后工作。假设我有html结构:

I am curious why when I replace .live() with .on() my events don't work after inserting AJAX's response via html() method. Assume I have html structure:

<div class="a">
   <a href="" class="alert-link">alert</a>
   <a href="" class="ajax-update">update</a>
</div>

和jquery代码类似:

and jquery code something like:

$('.alert-link').on("click", function(){
 alert('abc');
 return false;
});

和ajax-update将触发请求,响应将是

and ajax-update will trigger request, which response will be

提醒
更新

我会将其插入 parent()。然后再次按 alert-link 将导致重定向到 / ,但如果我更改 .on () .live()然后再次出现警报。我在这里错过了什么?我已经读过 .on()替换 .delegate()。住()

and I will insert it into parent(). Then pressing again alert-link will result in redirecting to / but if I change .on() to .live() then again alert will be shown. What am I missing here? I have read that .on() is replacement both for .delegate() and .live().

推荐答案

.on 合并并替换 .bind .live ,以及 .delegate 。语法 $('selector')。on('event',callback) bind 的道德等价物,不是直播

.on combines and replaces .bind, .live, and .delegate. The syntax $('selector').on('event', callback) is the moral equivalent of bind, not live.

为上的调用添加过滤选择器$ c>:

Add a filtering selector to your call to on:

$('container').on('click', 'child-filter', callback);

在这种情况下,

$('.a').on("click", ".alert-link", function(){
    alert('abc');
    return false;
});

这已被更改,因为将委托处理程序附加到比本地化程度更高的容器元素更有效旧的 .live 将处理程序附加到DOM的根目录的样式。

This was changed because it is more efficient to attach a delegate handler to a more localized container element than the old .live style of attaching the handler to the root of the DOM.

换句话说,即使 alert-link 元素只出现在一个小的 a div ,使用 .live ,jQuery监听页面上的每个单击事件并将其与委派的选择器进行比较。通过更有针对性,jQuery只需处理 a 中元素的点击。

In other words, even though alert-link elements will only appear inside of a small a div, with .live, jQuery listens to every single click event on the page and compares it to the delegated selector. By being more targeted, jQuery only has to process clicks on elements within a.

这篇关于jquery:on vs live的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆