jQuery 1.9/2.0/2.1及其以上 on 無(wú)效的解決辦法

字號(hào):


    jQuery 1.9/2.0/2.1及其以上版本無(wú)法使用live函數(shù)了,然而jQuery 1.9及其以上版本提供了on函數(shù)來代替。
    如果要綁定的on方法是動(dòng)態(tài)加載出來的元素,那么這樣使用就是沒有用的。
    <script>
    $(document).ready(function(){
    $(“#div1”).click(function(){
    $("<div class='test'>test</div>").appendTo($("#div1"));
    });
    $(“.test”).on(“click”,function(){
    $(".test").css("background-color","pink");
    });
    $(“#div2”).bind(“click”,function(){
    $(this).css("background-color","pink");
    });
    });
    $(document).ready(function(){
    $(“#div1”).click(function(){
    $("<div class='test'>test</div>").appendTo($("#div1"));
    });
    $(document).on(“click”,“.test”,function(){//修改成這樣的寫法
    $(".test").css("background-color","pink");
    });
    $(“#div2”).bind(“click”,function(){
    $(this).css("background-color","pink");
    });
    });
    究其元素就在于使用$(document)意義就在于使元素加載完后才執(zhí)行方法,所以當(dāng)為jQuery動(dòng)態(tài)加載的元素綁定on方法的時(shí)候,使用$(document)設(shè)置代碼腳本在DOM元素加載完成后開始執(zhí)行。