javascript jQuery:如何向动态添加的 HTML 元素添加事件处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5772018/
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
jQuery: How to add event handler to dynamically added HTML elements?
提问by Arihant Nahata
I have the following code:
我有以下代码:
$(document).ready(function({ $(".click").click(function(){ alert(' The Button Was Clicked !'); }); }));
This works fine.
But If I add an element with the same class to the web page, as shown here:
这工作正常。
但是如果我向网页中添加一个具有相同类的元素,如下所示:
$('#clicked').click(function(){ $("#area").append("<button class='click'>Click me</button>"); });
Then the event handler I added before to the .click class won't work for this new element.
What's that best way to add event handlers to elements that were added dynamically ?
然后我之前添加到 .click 类的事件处理程序将不适用于这个新元素。
将事件处理程序添加到动态添加的元素的最佳方法是什么?
回答by PeeHaa
UPDATE
更新
It's been a while since I posted this answer and things have changed by now:
我发布这个答案已经有一段时间了,现在情况已经发生了变化:
$(document).on('click', '.click', function() {
});
Since jQuery 1.7+ the new .on()
should be used and .live()
is deprecated. The general rule of thumb is:
从 jQuery 1.7+ 开始,.on()
应该使用new并且.live()
已弃用。一般的经验法则是:
- Don't use
.live()
unless your jQuery version doesn't support.delegate()
. - Don't use
.delegate()
unless your jQuery version doesn't support.on()
.
- 不要使用
.live()
,除非你的jQuery的版本不支持.delegate()
。 - 不要使用
.delegate()
,除非你的jQuery的版本不支持.on()
。
Also check out this benchmarkto see the difference in performance and you will see why you should not use .live()
.
另请查看此基准测试以了解性能差异,您将了解为什么不应该使用.live()
.
Below is my original answer:
以下是我的原答案:
use either delegate or live
使用委托或实时
$('.click').live('click', function(){
});
or
或者
$('body').delegate('.click', 'click', function() {
});
回答by Hacknightly
In reference to your code, the way to do it would be.
参考您的代码,这样做的方法是。
$('.click').live('click', function(){
... do cool stuff here
});
Using the .live() function allows you to dynamically attach event handlers to DOM objects. Have fun!
使用 .live() 函数可以让您动态地将事件处理程序附加到 DOM 对象。玩得开心!
回答by Lulli
After jQuery 1.7 the live method just points to .on() method. And I had alot trouble finding out how to bind event handler to element which is appended to the DOM after its loaded.
在 jQuery 1.7 之后,live 方法只指向 .on() 方法。而且我很难找到如何将事件处理程序绑定到加载后附加到 DOM 的元素。
$('body').live('click', '.click', function(){
//Your code
});
This worked for me. Just a little tip for those having trouble with it also.
这对我有用。对于那些遇到问题的人来说,这只是一个小技巧。
回答by kobe
for all the elements added dynamically to DOM at run time , please use live
对于在运行时动态添加到 DOM 的所有元素,请使用 live