元素绑定事件几种方式

一、javascript方式

1、HTML中添加onclick
  
  
<button id="vv" onclick="myfunction()" >哈哈</button>
2:JS中定义函数绑定事件!(写法一)
  
  
var funcc = function () {
  alert('我爱编程')
  }
var aa = document.getElementById('vv')
aa.onclick = funcc
3:直接定义函数与内容(写法二)
  
  
document.getElementById('vv').onclick = function () {
  alert('hasssshhaa ')
  }
4:利用addEventListener
document.getElementById('vv').addEventListener('click',funcc);
//或者:
document.getElementById('vv').addEventListener('click',function () {
  alert('hahah')
})
特殊:
1、
<div id="btn" onclick="clickone()" onclick="clicktwo()"></div>
<script>
   function clickone(){ alert("hello"); } //执行这个
   function clicktwo(){ alert("world!"); }
</script>

2、
<div id="btn"></div>
<script>
 document.getElementById("btn").onclick = function(){ alert("hello"); }
 document.getElementById("btn").onclick = function(){ alert("world"); } //执行这个
</script>

3、
<div id="btn"></div>
<script>
  document.getElementById("btn").addeventlistener("click",clickone,false);
  function clickone(){ alert("hello"); } //先执行
  document.getElementById("btn").addeventlistener("click",clicktwo,false);
  function clicktwo(){ alert("world"); } //后执行
</script>

二、jquery方式

1、简单事件绑定
这种绑定事件方式不会重叠(使用场景,场景:涉及dom操作-用户触发,这种情况一般dom都会加载完毕,没有影响,但是图片的长时间加载情况下,用户点击则出问题,Dom的操作用户触发。)
$(document).click(function () {
    alert(1);
})
但是有弊端,是我的表格数据分页有图片,第一页的可以,当我异步刷新表格后,无效。
2、bind方式(不推荐,1.7以后的jquery版本被on取代)
3、delegate(特点:性能高,支持动态创建的元素)
  
  
与前两种方式最大的优势:减少事件绑定次数提高效率,支持动态创建出来的元素绑定事件!
$(document).delegate(".box","click",function () {
      alert(1);
})
4、on方式(最现代方式,兼容zepto(移动端类似jquery的一个库),强烈建议使用的方式)--重点
$(document).on("click mouseenter",".box",{"name":111},function () {
    alert(event.data.name);
});
$(".box").on("click",{},function (e) {
    e.data
})

猜你喜欢

转载自www.cnblogs.com/liubao-xiaoqin/p/13385355.html
今日推荐