jquery的绑定事件有几种方式

来源:互联网 发布:淘宝客公司 编辑:程序博客网 时间:2024/06/06 08:33

jquery的绑定事件有几种方式 ,请举例说明其优缺点。

jQuery中提供了四种事件监听方式,分别是bind、live、delegate、on,对应的解除监听的函数分别是unbind、die、undelegate、off
a、bind()函数只针对已经存在的元素进行事件的设置。
live(),on.delegate()均支持未来新添加元素的事件设置。
b、bind()函数在jquery1.7版本以前比较受推崇,1.7版本出来之后,官方已经不推荐用bind(),
替代函数为on(),这也是1.7版本新添加的函数,同样,可以用来代替live()函数,live()函数在1.9版本已经删除;
c、bind()、.live()或.delegate(),查看源码就会发现,它们实际上调用的都是.on()方法
d、移除.on()绑定的事件用.off()方法。
e、bind()支持Jquery所有版本,live()支持jquery1.9-,delegate()支持jquery1.4.2+,on()支持jquery1.7+

on()函数的使用

多个事件绑定同一个函数

$(document).ready(function(){

  $("p").on("mouseover mouseout",function(){

    $("p").toggleClass("intro");

  });

});

多个事件绑定不同函数

$(document).ready(function(){

  $("p").on({

    mouseover:function(){$("body").css("background-color","lightgray");},  

    mouseout:function(){$("body").css("background-color","lightblue");}, 

    click:function(){$("body").css("background-color","yellow");}  

  });

});

用on()方法绑定多个选择器,多个事件则可以这样写:

$(document).on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    click: function() {
        // Handle click...
    }
}, '#header .fixed-feedback-bn, #sb-sec .feedback-bn');

绑定自定义事件

$(document).ready(function(){

  $("p").on("myOwnEvent", function(event, showName){

    $(this).text(showName + "! What a beautiful name!").show();

  });

  $("button").click(function(){

    $("p").trigger("myOwnEvent",["Anja"]);

  });

});

传递数据到函数

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");

  });

});

tip:如果你需要移除on()所绑定的方法,可以使用off()方法处理。

$(document).ready(function(){

  $("p").on("click",function(){

    $(this).css("background-color","pink");

  });

  $("button").click(function(){

    $("p").off("click");

  });

});

在需要为较多的元素绑定事件的时候,优先考虑事件委托,可以带来性能上的好处。将click事件绑定在document对象上,页面上任何元素发生的click事件都冒泡到document对象上得到处理。