jquery的on()方法总结

jquery的on()方法总结

摘自菜鸟教程 废话不说 直接上demo

实例:

向<p>元素添加click事件处理程序:

 1 <html>
 2 <head>
 3 <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
 4 </script>
 5 <script>
 6 $(document).ready(function(){
 7   $("p").on("click",function(){
 8     alert("段落被点击了。");
 9   });
10 });
11 </script>
12 </head>
13 <body>
14 
15 <p>点击这个段落。</p>
16 
17 </body>
18 </html>

运行结果:

定义和用法:

1. on() 方法在被选元素及其子元素上添加一个或多个 事件处理程序

2.自jquery1.7版本之后 on()方法是bind() live() delegate() 方法新的替代品 推荐使用此方法!使用其他的方法可能会出现不兼容的问题

3.使用on()方法添加的事件程序适用于当前未来的程序(这里的未来的程序是脚本创建新元素,或者是以前的事件代理程序)

4. 如果要移除使用on()方法添加的事件处理程序 请使用与之对应的off()方法

5.如果你想事件执行一次就移除请使用one()方法

6.on()方法支持自定义事件

语法:

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

参数说明:

event 必须  事件的名称(可以自定义) 支持绑定多个事件 多个事件用空格分开 也可以是map参数和数组

childSelector 可选 添加事件程序的子元素而且不是父选择器本身

data  可选 传递到事件对象 event的额外的参数

function 必选 规定事件发生时运行的函数

实例分析:

bind()改为on() 

<!DOCTYPE html>
<html>
<head>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#div1").on("click",function(){
    $(this).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>

运行结果:

运行结果2:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值