如何使用 jQuery 在動態建立的元素上繫結事件?


若要將事件繫結到動態建立的元素,你需要動態載入。你可以嘗試執行以下程式碼來了解如何在動態建立的元素上繫結事件。這裡,我們將透過單擊按鈕生成新的列表項。

示例

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/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'>&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>

更新於: 2020 年 2 月 14 日

2K+ 瀏覽量

開啟您的 職業生涯

完成課程認證

立即開始
廣告
© . All rights reserved.