在jQuery中将live()转换为on() [英] Turning live() into on() in jQuery

查看:437
本文介绍了在jQuery中将live()转换为on()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序动态添加了Dropdown。用户可以根据需要添加任意数量的内容。

My application has dynamically added Dropdowns. The user can add as many as they need to.

我传统上使用jQuery的 live()方法检测其中一个Dropdown是 change() ed:

I was traditionally using jQuery's live() method to detect when one of these Dropdowns was change()ed:

$('select[name^="income_type_"]').live('change', function() {
    alert($(this).val());
});

从jQuery 1.7开始,我已将此更新为:

As of jQuery 1.7, I've updated this to:

$('select[name^="income_type_"]').on('change', function() {
    alert($(this).val());
});

查看文档,这应该是完全有效的(对吧?) - 但事件处理程序永远不会触发。当然,我已经确认jQuery 1.7已经加载并运行等等。错误日志中没有错误。

Looking at the Docs, that should be perfectly valid (right?) - but the event handler never fires. Of course, I've confirmed jQuery 1.7 is loaded and running, etc. There are no errors in the error log.

我做错了什么?谢谢!

推荐答案

on 文档状态(粗体;)):

The on documentation states (in bold ;)):


事件处理程序受约束仅限于当前选定的元素;在您的代码调用 .on()时,它们必须存在于页面上。

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

相当于 .live()类似于

$(document.body).on('change', 'select[name^="income_type_"]', function() {
    alert($(this).val());
});

尽管将事件处理程序尽可能地绑定到元素上会更好,也就是说,在层次结构中靠近一个元素。

Although it is better if you bind the event handler as close as possible to the elements, that is, to an element being closer in the hierarchy.

更新:在回答另一个问题时,我发现中也提到了这个问题。 href =http://api.jquery.com/live/> .live 文档

Update: While answering another question, I found out that this is also mentioned in the .live documentation:


根据其后继者重写 .live()方法很简单;这些是用于所有三种事件附件方法的等效调用的模板:

Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+


这篇关于在jQuery中将live()转换为on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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