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