jQuery動態添加的節時間點事件無法觸發

來源:互聯網
上載者:User

標籤:https   col   UI   添加   com   父類   cli   解決   無法   

添加節點之前

點擊圖中的 "第一個" 之後會觸發click事件,效果

 

點擊按鈕的之後,添加節點之後

這時點擊圖中的 "第一個",卻不會觸發click事件。

此時代碼如下: 

<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><html><head><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script><script>    $(function(){        $(".a1").on("click",function(){            alert("觸發a標籤的點擊事件!");        });        });        function cl(){        $(".div2").html(‘<a class="a1">第一個</a><br><a class="a2">第二個</a>‘);    }</script></head><body>    <div class="div1">        <div class="div2">            <a class="a1">第一個</a>                    </div>        <input onclick="cl()" type="button" value="添加節點"/>    </div></body></html>

以上問題可以通過綁定幾種方法解決

1.是直接在添加標籤的時候添加一個onclick事件;

2.通過綁定這個標籤的父類或者body來達到啟用click事件的效果。

改過之後的代碼如下:

<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><html><head><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script><script>    $(function(){        /*$(".a1").on("click",function(){            alert("觸發a標籤的點擊事件!");        });*/                    /*$(".div1").on("click",".a1",function(){            alert("觸發a標籤的點擊事件!");        });*/                $(".div2").on("click",".a1",function(){            alert("觸發a標籤的點擊事件!");        });                /*$("body").on("click",".a1",function(){            alert("觸發a標籤的點擊事件!");        });*/    });        function cl(){        $(".div2").html(‘<a class="a1">第一個</a><br><a class="a2">第二個</a>‘);    }</script></head><body>    <div class="div1">        <div class="div2">            <a class="a1">第一個</a>                    </div>        <input onclick="cl()" type="button" value="添加節點"/>    </div></body></html>

如果出現,點擊一次,出現兩次click事件的話,

考慮使用propagation()方法處理冒泡。

jQuery動態添加的節時間點事件無法觸發

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.