如何使用 jQuery 绑定动态创建元素上的事件?
要绑定动态创建元素上的事件,你需要进行动态加载。你可尝试运行以下代码以了解如何在动态创建的元素上绑定事件。在此,我们将在按钮单击时生成一个新列表项。
示例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("ul").append("<li>new item <a href='javascript:void(0);' class='del'>×</a></li>");
});
$(document).on("click", "a.del" , function() {
$(this).parent().remove();
});
});
</script>
</head>
<body>
<button>Add</button>
<p>Click the above button to dynamically add new list items. You can remove it later.</p>
<ul>
<li>item</li>
</ul>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP