码迷,mamicode.com
首页 > Web开发 > 详细

jQuery 1.9/2.0/2.1及其以上 on 无效的解决办法

时间:2015-04-15 16:20:33      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

http://www.zhidao91.com

jQuery on函数语法 

$(selector).on(event,childSelector,data,function,map)

  

参数 描述
event 必需。规定要从被选元素移除的一个或多个事件或命名空间。由空格分隔多个事件值。必须是有效的事件。
childSelector 可选。规定只能添加到指定的子元素上的事件处理程序(且不是选择器本身,比如已废弃的 delegate() 方法)。
data 可选。规定传递到函数的额外数据。
function 可选。规定当事件发生时运行的函数。
map 规定事件映射 ({event:function, event:function, …}),包含要添加到元素的一个或多个事件,以及当事件发生时运行的函数。
<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("p").on("click",function(){
    alert("The paragraph was clicked.");
  });
});
</script>
</head>
<body>
 
<p>Click this paragraph.</p>
 
</body>
</html>

正常情况下上面这段是可以实现的。但是如果要绑定的on方法是动态加载出来的元素,那么这样使用就是没有用的。看下面的例子:

<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(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");
  });
});
</script>
</head>
<body>
 
<h4 style="color:green;">This example demonstrates how to achieve the same effect using on() and bind().</h4>
 
<div id="div1" style="border:1px solid black;">This is some text.
<p>Click to set background color using the <b>on() method</b>.</p>
</div><br>
 
<div id="div2" style="border:1px solid black;">This is some text.
<p>Click to set background color using the <b>bind() method</b>.</p>
</div>
 
</body>
</html>

究其元素就在于使用$(document)意义就在于使元素加载完后才执行方法,所以当为jQuery动态加载的元素绑定on方法的时候,使用$(document)设置代码脚本在DOM元素加载完成后开始执行。

在jquery1.7的时候直接用live即可以实现动态绑定

jQuery 1.9/2.0/2.1及其以上 on 无效的解决办法

标签:

原文地址:http://www.cnblogs.com/JAYIT/p/4428515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!