jQuery 1.9/2.0/2.1及其以上版本沒法使用live函數了,然而jQuery 1.9及其以上版本提供了on函數來代替。 若是要綁定的on方法是動態加載出來的元素,那麼這樣使用就是沒有用的。css
<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"); }); }); </script>app
$(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)意義就在於使元素加載完後才執行方法,因此當爲jQuery動態加載的元素綁定on方法的時候,使用$(document)設置代碼腳本在DOM元素加載完成後開始執行。this