jQuery事件绑定

先看看 jQuery事件绑定和JavaScript事件绑定的区别

为一个id为Mydiv的元素添加多个事件

用JavaScript原生添加事件如下:

var btn = document.getElementById("Mydiv");
btn.onclick = function(){
	alert(1);
}
btn.onclick = function(){
	alert(2);
}

执行上面的代码只会alert 2 

用 jQuery 添加事件如下:

$btn = $("#Mydiv")
$btn.click(function(){
  alert("1");
})
$btn.click(function(){
  alert("2");
})

执行上面的代码会先alert 1 再 alert 2 。再看下面

$("#Mydiv").on("click",function(){
  alert(1);
}).on("click",function(){
  alert(2);
});

执行上面的代码会先alert 1 再 alert 2

以上可以说明 jQuery 中的事件绑定具有叠加性,JavaScript原生的事件绑定则是可覆盖的。

那么 jQuery 中事件绑定方式有几种?

方式一 <bind>:  绑定: $(selector).bind("事件名",data,function)

        解绑: $(selector).unbind("事件名",handler)

$("#Mydiv").bind("click",function(){
  alert("1");
 }).bind("click",function(){
  alert("2");
 });

还可以这样:

$("#Mydiv").bind({
 click:function() {
  console.log("疼")
 },
 mouseenter:function() {
      console.log("鼠标进入")
 },
mouseleave:function(){
  console.log("鼠标离开")
}
});

方式二 <one>:  $("选择器").one("事件名",function) 只能触发一次,触发后,自动解绑

$("#Mydiv").one("mouseenter",function(){
  $(this).css("background","red")
}).one("click",function(){
  $(this).css("background","yellow")
});

方式三 <delegate> : 绑定: $("父元素").delegate("子元素","事件名",function);

          解绑: $(selector).undelegate("事件名",handler)

就是可以为一个或多个子元素绑定事件

$("ul").delegate("li","click",function(e){
$(this).css("background","red");
})

方式四 <on> : 绑定: $("选择器").on("事件名","选择器",function)

        解绑: $(selector).off("事件名",handler)

$(document).on("click","a",function(){

  $(this).css("background","#000")
}).on("click","p",function(){
  $(this).css("background","yellow")
}).on("click","h1",function(){
  $(this).css("background","red")
});

还可以这样:

$(document).on("click",function(){
  $("a").css("background","#000")
}).on("click",function(){
  $("p").css("background","yellow")
}).on("click",function(){
  $("div").css("background","red")
});

不同之处有?

绑定位置 :
.bind() 直接绑在目标元素(子元素)上
.delegate() 绑在父元素上

事件监听的个数:
.bind() 导致事件监听个数增多
.delegate() 始终只有一个监听

未来子元素:

bind() 无法让动态生成的新元素自动获得事件处理函数

.delegate() 即使后来动态生成的新元素也可自动获得父元素上的事件处理函数

 

原文地址:https://www.cnblogs.com/lan-cheng/p/8414645.html