jQuery目前有on(),bind(),delegate(),live()四种绑定方式,但是随着版本的不断更新,有的方式也相应的被淘汰掉

【band()方式绑定】

3.0版本之前的绑定方式比较常用的是bind()绑定事件,解除事件的方式是unbind(),但是在3.0之后band()的绑定方式也别相应的解除掉了。bind()的事件绑定是只对当前页面选中的元素有效。如果你想对动态创建的元素bind()事件,是没有办法达到效果的,如下代码。

 <body>
<button id="add" type="button">add DIV</button>
<button id="del" type="button">del DIV</button>
<button id="onBtn" type="button">绑定事件</button>
<button id="offBtn" type="button">解绑事件</button>
<div id="container">
<div class='created'>我是原生div<div/>
</div>
</body>
<script>
$(function () {
$("#add").click(function(){
$("#container").prepend("<div class='created'>我是动态生成的div<div/>")
});
$("#del").click(function(){
$("div").remove(".created:first")
});
$("#onBtn").click(function(){
$("#container").on("click",".created",function(){
alert(1);
});
});
$("#offBtn").click(function(){
$("#container").off("click");
})
})
</script>

delegate(),live()两种绑定方式并不太常用,因此推荐下面这种方式,on()绑定。

【on()事件绑定】

① 使用on进行单事件绑定

$("button").on("click",function(){
$(this) 取到当前调用事件函数的对象
console.log($(this).html());
});

② 使用on同时为多个事件,绑定同一函数
$("button").on("mouseover click",function(){
console.log($(this).html())
});

③ 调用函数时,传入自定义参数
$("button").on("click",{name:"jianghao"},function(event){
使用event.data.属性名 找到传入的参数
console.log(event.data.name);
})

④ 使用on进行多事件多函数绑定
$("button").on({
click:function(){
console.log("click")
},
mouseover:function(){
console.log("mouseOver")
}
});

⑤ 使用on进行事件委派
 >>> 将原本需要绑定到某元素上的事件,改为绑定在父元素乃至根节点上,然后委派给当前元素生效;
eg:$("p").click(function(){});
 $(document).on("click","p",function(){});
作用:
默认的绑定方式,只能绑定到页面初始时已有的p元素,当页面新增p元素时,无法绑定到新元素上;
使用事件委派方式,当页面新增元素时,可以为所有新元素绑定事件

off() 取消事件绑定
1. $("p").off(): 取消所有事件
2. $("p").off("click"): 取消点击事件
3. $("p").off("click mouseover"):取消多个事件
4. $(document).off("click","p"):取消事件委派

最新文章

  1. [速记]关于指针,引用和递归和解递归——C++
  2. powerdesigner-从excel导入table模型
  3. MVC与webservice上传文件(图片和视频),希望帮且到一些朋友
  4. git 使用入门
  5. Ubuntu 16.04播放器Rhythmbox乱码解决
  6. Android中“再按一次返回键退出程序”实现
  7. eclipse安装maven插件
  8. 【转】 UINavigationItem UINavigationBar 关系分析
  9. Expanding Rods(二分)
  10. oracle开机自启动-超简单
  11. windows下配置lamp环境(0)---软件获取
  12. 关于OC中的几种代码延迟执行方式
  13. css系列教程--文本
  14. Mysql的基本命令图
  15. Android利用ViewPager仿微信主界面-android学习之旅(78)
  16. 轻松理解 Java HashMap 和 ConcurrentHashMap
  17. 【译】为什么BERT有3个嵌入层,它们都是如何实现的
  18. ABP框架系列之二十七:(Feature-Management-特征管理)
  19. Kafka、RabbitMQ、RocketMQ等消息中间件的对比
  20. BGP - 3,BGP重要概念(EBGP,IBGP,防环/黑洞/全互连/同步)

热门文章

  1. 项目部署到服务器上之后request.getRemoteAddr()为什么获取的都是本地地址
  2. 2019.03.01 bzoj2555: SubString(sam+lct)
  3. Git+Github入门
  4. docer compose学习
  5. ELK部署与使用总结
  6. ReSharper 10.0.0.1 Ultimate 完美破解补丁使用方法
  7. EF6 学习笔记(三):排序、过滤查询及分页
  8. django-celery 创建多个broker队列 异步执行任务时指定队列
  9. poj1149构图题
  10. What does git fsck stand for?