参考博客:https://blog.csdn.net/ditto_zhou/article/details/62042670
一、jquery的几种事件绑定方式: bind(),on(),live(),delegate()
1.bind()函数只能针对已经存在的元素进行事件的设置;但是live(),on(),delegate()均支持未来新添加元素的事件设置;
2.bind()函数在jquery1.7版本以前比较受推崇,1.7版本出来之后,官方已经不推荐用bind(),替代函数为on(),这也是1.7版本新添加的函数,同样,可以来代替live()函数,live()函数在1.9版本已经删除;
3.live()函数和delegate()函数两者类似,但是live()函数在执行速度,灵活性和CSS选择器支持方面较delegate()差些
4.bind()支持Jquery所有版本;live()支持jquery1.9-;delegate()支持jquery1.4.2+;on()支持jquery1.7+;
二、推荐使用on()方法
1. on方法可以动态绑定添加到页面元素的事件 ;
2 .on方法效率更高;
3. on 的使用
-- 多个事件绑定一个函数
//多个事件绑定一个方法
$(function(){
$("p").on('mouseover mouseout',function(){
alert(1111);
});
});
-- 多个事件绑定多个函数
//多个事件绑定不同的方法
$(function(){
$("a").on({
mouseover:function(){$("t1").css('background-color','red');},
mouseout:function(){$("t2").css('background-color','yellow');},
click:function(){$("t3").css('background-color','blue');}
});
});
--绑定自定义事件
$(document).ready(function(){
$("p").on("myevent", function(event, showName){
$(this).text(showName + "! What a beautiful name!").show();
});
$("button").click(function(){
$("p").trigger("myevent",["helloworld"]);
});
});
-- 用于未创建的元素
//适用于未创建的元素
$(document).ready(function(){
$("div").on("click","p",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
);
});
-- 如果需要移除on方法绑定的事件
//移除on方法绑定的事件 可以使用off方法
$(document).ready(function(){
$("p").on("click",function(){
$(this).css("background-color","pink");
});
$("button").click(function(){
$("p").off('click');
});
});