jquery 新增html元素後 html中click失效問題

航空母艦發表於2015-03-18

jqeury 新增html 元素後 .click 失效問題

<script>
    function xxx() {
        var abc = '<li><h3 class="geegee">3</h3></li>';
        var acc = '<li><h3 class="geegee">4</h3></li>';
        output = $(abc + acc);
        $('#category').append(output);
    }
</script>

<script>
    $(document).ready(function() {
        $(".geegee").click(function() { //bug
            alert("a");
        });
    });
</script>

自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。該方法給 API 帶來很多便利,我們推薦使用該方法,它簡化了 jQuery 程式碼庫。使用 on() 方法新增的事件處理程式適用於當前及未來的元素(比如由指令碼建立的新元素)

$(".geegee").on("click",function() {
    alert("a");
});

委派事件

$("#category").delegate(".geegee","click",function(evt) {
    alert("a");
    evt.stopPropagation();
});

ss

 

 

 

 
 

相關文章