如何使用 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'>×</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>
廣告