Jquery添加事件监听器以动态添加元素 [英] Jquery adding event listeners to dynamically added elements

查看:102
本文介绍了Jquery添加事件监听器以动态添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以现在我明白为了将一个事件监听器附加到一个动态添加的元素中,你必须在添加元素后重新定义监听器。有没有办法绕过这个,所以你不必执行一个额外的代码块?

So right now, I understand that in order to attach an event listener to a dynamically added element, you have to redefine the listener after adding the element. Is there any way to bypass this, so you don't have to execute a whole extra block of code?

推荐答案

使用< a href =http://api.jquery.com/on/ =noreferrer> .on() 您可以定义您的功能一次,它将为任何动态添加的元素执行。

Using .on() you can define your function once, and it will execute for any dynamically added elements.

例如

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});

这篇关于Jquery添加事件监听器以动态添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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