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()差些,想了解具体情况,请戳这:
http://kb.cnblogs.com/page/94469/
4.bind()支持Jquery所有版本;live()支持jquery1.9-;delegate()支持jquery1.4.2+;on()支持jquery1.7+;
推荐使用 .on()绑定事件的方式 :
1. on方法可以动态绑定添加到页面元素的事件
比如动态添加到页面的DOM元素,不用担心注册事件的元素什么时候被添加进来,也不用重复绑定
live(),bind(),delegate()底层都是使用的是on()
2 .on方法可以提升效率
$('li').click(function(){ alert(111);});
$(document).on('click','li',function(){ alert(222222)}); //经过测试效率会更高
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"]);
});
});
-- 传递数据到函数
//传递数据到函数
function handlerName(event){
alert(event.data.msg);
}
$(document).ready(function(){
$("p").on("click", {msg: "You just clicked me!"}, handlerName)
});
-- 用于未创建的元素
//适用于未创建的元素
$(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');
});
});