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

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

问题描述

我的应用程序动态添加了下拉菜单.用户可以根据需要添加任意数量.

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

我传统上使用 jQuery 的 live() 方法来检测这些下拉菜单之一何时被 change()

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.

更新:在回答另一个问题时,我发现中也提到了这一点.实时文档:

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天全站免登陆