這篇文章主要介紹了jquery append 動態添加的元素事件on 不起作用的解決方案,需要的朋友可以參考下
用jquery添加新元素很容易,面對jquery append 動態添加的元素事件on 不起作用我們該如何解決呢?on方法中要先找到原選擇器(如例.info),再找到動態添加的選擇器(如列.delete)。
具體不多說了,請看下面的代碼吧。
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>測試</title>
- <script type="text/javascript"
- src="../resources/js/jquery-1.11.1.min.js"></script>
- <script type="text/javascript">
- $(function(){
- //動態添加
- $(".add").on("click",function(){
- console.log("進來了");
- $(".info").append('<div class="delete"><h3>單擊我來刪除我</h3></div>');
- });
- //對動態添加的元素添加事件-刪除
- $(".info").on("click",".delete",function(){
- console.log("進來了Delete!");
- $(this).remove();
- });
- });
- </script>
- </head>
- <body>
- <h2 class='add'>單擊我添加動態元素</h2>
- <div class="info"></div>
- </body>
- </html>
以上代碼就是本文對jquery append 動態添加的元素事件on 不起作用的解決方案,希望對大家學習有所幫助。
新聞熱點
疑難解答
圖片精選