zoukankan      html  css  js  c++  java
  • jQuery中bind,live,delegate,on的区别

    bind(),live()都是调用on()函数,只不过传递的参数不同。

    一、$(selector).bind(event,data,fn);

    $('#J_btn').bind('click',function(){
      //直接绑定在指定元素上
      //只能针对已经存在的元素进行事件的设置
    });

    二、$(selector).live(event,data,fn);

    $('#J_btn').live('click',function(){
      //委托,绑定在父元素上,父元素只能是document
      //live可以实现动态绑定
      //通过冒泡的方式来绑定到元素上
      //支持未来新添加元素的事件设置
    });

    三、$(selector).delegate(childSelector,event,data,fn);

    $("#J_btn").delegate("J_btn_left","click",function(){
      //委托,绑定在父元素上,父元素可以是任意的祖先节点
      //delegate可以实现动态绑定
      //通过冒泡的方式来绑定到元素上
      //支持未来新添加元素的事件设置
    });

    四、$(selector).on(event,childselector,data,fn);

    $("#J_btn").on("click","J_btn_left",function(){
      //支持未来新添加元素的事件设置
    });

    jQuery推出on()的目的有2个,一是为了统一接口,二是为了提高性能,所以从现在开始用on()替换bind(), live(), delegate()吧。尤其是不要再用live()了,因为它已经处于不推荐使用列表了,随时会被干掉。如果只绑定一次事件,那接着用one()吧,这个没有变化。bind()支持Jquery所有版本;live()支持jquery1.8-;delegate()支持jquery1.4.2+;on()支持jquery1.7+。
    五、事件处理
    1、单事件处理

    $(selector).on("click",data,fn);

    2、多事件处理

    A、利用空格分割多事件

    $(selector).on("click dbclick mouseout",childselector,data,fn);

    B、利用大括号灵活定义多事件

    $(selector).on({
        event1:fn,
        event2:fn,
        ...
    });

    C、链式绑定事件

    $(selector)
    .on("click",childselector,data,fn)
    .on("dbclick",childselector,data,fn)
    .on("mouseout",childselector,data,fn);

    unbind(),die()和undelegate()方法也合并成了off()方法。

  • 相关阅读:
    Android开发使用Glide获取图片背景色淡绿色解决办法
    Android 获取 View 宽高的常用正确方式,避免为零
    Android之自定义View来接收输入法输入的内容
    FileProvider使用详解(拍照、安装APP、共享文件)
    简明 homebrew
    更优雅地使用命令行
    一篇长文说 git 基础
    chrome 浏览器的使用技巧
    前端学命令行
    cocos 碰撞系统
  • 原文地址:https://www.cnblogs.com/camille666/p/jquery_bind_live_delegate_on.html
Copyright © 2011-2022 走看看