Javascript jQuery - 如何使用“on()”方法而不是“live()”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14703646/
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 17:40:40  来源:igfitidea点击:

jQuery - how to use the "on()" method instead of "live()"?

javascriptdeprecatedjqueryjquery-on

提问by Morteza

I used live()for generated pages and frames. But in jQuery 1.9this function is deprecated and does not work.

我用于live()生成的页面和框架。但在jQuery 1.9此功能中已弃用且不起作用。

I use on()instead of live()but this method works for one time, and does not work in frames.

我使用on()而不是,live()但此方法仅适用一次,并且不适用于帧。

My code looks like this:

我的代码如下所示:

  $("#element").live('click',function(){
    $("#my").html(result);
   });

What is the solution?

解决办法是什么?

回答by Samuel Liew

$('body').on('click', '#element', function(){
    $("#my").html(result);
});

The clicked element selector is now passed through the .on()function parameters, and the previous selector should be replaced with the closest parent selector preferably with an ID. If you do not know what parent selector to use, bodyworks too, but is less efficient.

单击的元素选择器现在通过.on()函数参数传递,并且应该用最近的父选择器替换前一个选择器,最好是带有 ID。如果您不知道要使用哪个父选择器,body也可以使用,但效率较低。

see jQuery 1.9 .live() is not a functionon how to migrate existing code.

请参阅jQuery 1.9 .live() 不是关于如何迁移现有代码的函数