如何使用jQuery在动态创建的元素上绑定事件?

要在动态创建的元素上绑定事件,您需要动态加载。您可以尝试运行以下代码,以了解如何在动态创建的元素上绑定事件。在这里,我们将在单击按钮时生成一个新的列表项。

示例

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/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'>&times;</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>