Javascript 在 jQuery 中将 live() 转换为 on()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8021436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:23:53  来源:igfitidea点击:

Turning live() into on() in jQuery

javascriptjqueryjquery-1.7

提问by Hyman

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

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

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

我传统上使用 jQuery 的live()方法来检测这些 Dropdowns 之一何时被change()编辑:

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

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

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

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

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.

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

What am I doing wrong? Thanks!

我究竟做错了什么?谢谢!

回答by Felix Kling

The ondocumentationstates (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().

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

Equivalent to .live()would be something like

相当于.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 .livedocumentation:

更新:在回答另一个问题时,我发现.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+

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

$(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+

回答by Vikrant Chaudhary

In addition to the selected answer,

除了选择的答案,

Port jQuery.liveto jQuery 1.9+ while you wait for your application to migrate. Add this to your JavaScript file.

端口jQuery.live将jQuery 1.9+,而你等待你的应用程序迁移。将此添加到您的 JavaScript 文件中。

// Borrowed from jQuery 1.8.3's source code
jQuery.fn.extend({
  live: function( types, data, fn ) {
          if( window.console && console.warn ) {
           console.warn( "jQuery.live is deprecated. Use jQuery.on instead." );
          }

          jQuery( this.context ).on( types, this.selector, data, fn );
          return this;
        }
});

Note:Above function will not work from jQuery v3 as this.selectoris removed.

注意:上面的函数在 jQuery v3 中将不起作用,因为它this.selector被删除了。

Or, you can use https://github.com/jquery/jquery-migrate

或者,您可以使用https://github.com/jquery/jquery-migrate

回答by Tony Wall

Just found a better solution which doesn't involve editing third party code:

刚刚找到了一个更好的解决方案,它不涉及编辑第三方代码:

https://github.com/jquery/jquery-migrate/#readme

https://github.com/jquery/jquery-migrate/#readme

Install the jQuery Migrate NuGet package in Visual Studio to make all the versioning issues go away. Next time Microsoft update their unobtrusive AJAX and validation modules perhaps try it without the migrate script again to see if they resolved the issue.

在 Visual Studio 中安装 jQuery Migrate NuGet 包以消除所有版本控制问题。下次 Microsoft 更新其不显眼的 AJAX 和验证模块时,可能会在没有迁移脚本的情况下再次尝试,看看他们是否解决了问题。

As jQuery Migrate is maintained by the jQuery Foundation I think this is not only the best approach for third party libraries and also to get warning messages for your own libraries detailing how to update them.

由于 jQuery Migrate 由 jQuery Foundation 维护,我认为这不仅是第三方库的最佳方法,也是获取您自己的库的警告消息,详细说明如何更新它们。

回答by Maykol Rypka

In addition to the selected answers,

除了选定的答案,

If you use Visual Studio, you can use the Regex Replace.
In Edit > Find and Replace > Replace in Files
Or Ctrl + Shift + H

如果您使用Visual Studio,则可以使用Regex Replace
在编辑 > 查找和替换 > 在文件中替换
或 Ctrl + Shift + H

In Find and Replace pop-up, set these fields

在查找和替换弹出窗口中,设置这些字段

Find what:\$\((.*)\)\.live\((.*),
Replace with:$(document.body).on($2,$1,
In find options check "Use Regular Expressions"

查找内容:\$\((.*)\)\.live\((.*),
替换为:$(document.body).on($2,$1,
在查找选项中选中“使用正则表达式”

回答by U?ur Tosun

jquery verision x.x.x.js open editor, find jQuery.fn.extend

jquery 版本 xxxjs 打开编辑器,找到 jQuery.fn.extend

add code

添加代码

live: function( types, data, fn ) {
        jQuery( this.context ).on( types, this.selector, data, fn );
        return this;
    },

Example : jquery-2.1.1.js --> line 7469 (jQuery.fn.extend)

示例:jquery-2.1.1.js --> 第 7469 行 (jQuery.fn.extend)

Example images view

示例图像视图