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?

推荐答案

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相关问答推荐

JQuery - 从先前 Select 的下拉列表中隐藏/显示选项

JQuery:$.get 不是函数

Jquery如何通过数组中的属性查找对象

何时执行 $(document).ready 回调?

在 jQuery 中,我想删除 div 中的所有 HTML

Bootstrap 3 RC 1 中的 typeahead JavaScript 模块在哪里?

如何在单击时 Select 多选 Select 框的所有选项?

可以在删除类时反转css动画吗?

在 HTML 表单提交上制作 Enter 键而不是激活按钮

jQuery用另一个类替换一个类

使用 JQuery / JavaScript 调用/单击 mailto 链接

如何检测 window.print() 完成

.apply jQuery 函数是什么?

$(document).on("click"... 不工作?

如何使用 jQuery 或纯 JS 重置所有复选框?

jquery更改div类的样式属性

Uncaught TypeError: undefined is not a function on loading jquery-min.js

如何确定滚动高度?

在 Firefox 上开发的 Javascript 在 IE 上失败的典型原因是什么?

清除表jquery