Home Web Front-end JS Tutorial Detailed explanation of bind(), live(), delegate(), on() binding event method examples in jQuery_jquery

Detailed explanation of bind(), live(), delegate(), on() binding event method examples in jQuery_jquery

May 16, 2016 pm 03:19 PM
bind jquery live on Binding events

This article analyzes the bind(), live(), delegate(), and on() binding event methods in jQuery through examples. Share it with everyone for your reference, the details are as follows:

Foreword

Because jquery is often used to add and delete dom elements in the project, it will involve the binding event method of dom elements. I will briefly summarize the differences between bind, live, delegate and on for future reference. I also hope This article can help all my friends in the future. If there is anything inappropriate in the article, I hope you will correct me. Without further ado, let’s get straight to the point.

1. bind()

Brief description

bind() adds one or more event handlers to the matching element.

How to use

Copy code The code is as follows:
$(selector).bind(event,data,function)

event: required; one or more events added to the element, such as click, dblclick, etc.;

Single event processing: For example,

Copy code The code is as follows:
$(selector).bind("click" ,data,function);

Multiple event processing: 1. Use spaces to separate multiple events, such as
Copy code The code is as follows:
$(selector). bind("click dbclick mouseout",data,function);

2. Use braces to flexibly define multiple events, such as
Copy the code The code is as follows:
$(selector).bind( {event1:function, event2:function, ...})

3. Space separation method: Binding is relatively rigid and cannot bind functions to events individually. It is suitable for handling multiple events calling the same function;

Braces alternative: binding is more flexible and you can bind functions to events separately;

data: optional; parameters that need to be passed;
function: required; function that needs to be executed when a binding event occurs;

Examples

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>jquery中bind()绑定事件方式</title>
  <style type="text/css">
    .container
    {
      width: 300px;
      height: 300px;
      border: 1px #ccc solid;
      background-color: Green;
    }
    .btn-test
    {
      border: 1px #ccc solid;
      padding: 5px 15px;
      cursor: pointer;
    }
  </style>
  <script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      /*********添加单个事件处理*********/
      $(".btn-test").bind("click", function () {
        //显示隐藏div
        $(".container").slideToggle();
      });
      /********添加多个事件处理********/
      //空格相隔方式
      $(".btn-test").bind("mouseout click", function () {
        //显示隐藏div
        $(".container").slideToggle();
      });
      //大括号替代方式
      $(".btn-test").bind({
        "mouseout": function () {
          alert("这是mouseout事件!");
        },
        "click": function () {
          $(".container").slideToggle();
        }
      });
      /********删除事件处理********/
      $(".btn-test").unbind("click");
    });
  </script>
</head>
<body>
  <input type="button" value="按钮" class="btn-test" />
  <div class="container">
  </div>
</body>
</html>

Copy after login

Applicable Jquery version

Applicable to all versions, but according to the official website, since jquery 1.7 version, the bind() function is recommended to be replaced by on().

2. live()

Brief description

live() adds one or more event handlers to the current or future matching elements;

How to use

Copy code The code is as follows:
$(selector).live(event,data,function)

event: required; one or more events added to the element, such as click, dblclick, etc.;

Single event processing: For example,

Copy code The code is as follows:
$(selector).live("click" ,data,function);

Multiple event processing: 1. Use spaces to separate multiple events, such as
Copy code The code is as follows:
$(selector). live("click dbclick mouseout",data,function);

2. Use braces to flexibly define multiple events, such as
Copy the code The code is as follows:
$(selector).live( {event1:function, event2:function, ...})

3. Space separation method: Binding is relatively rigid and cannot bind functions to events individually. It is suitable for handling multiple events calling the same function;

Braces alternative: binding is more flexible and you can bind functions to events separately;

data: optional; parameters that need to be passed;
function: required; function that needs to be executed when a binding event occurs;

Examples

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>jquery中live()绑定事件方式</title>
  <style type="text/css">
    .container
    {
      width: 300px;
      height: 300px;
      border: 1px #ccc solid;
      background-color: Green;
    }
    .btn-test
    {
      border: 1px #ccc solid;
      padding: 5px 15px;
      cursor: pointer;
    }
  </style>
  <script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      /*********添加单个事件处理*********/
      $(".btn-test").live("click", function () {
        //显示隐藏div
        $(".container").slideToggle();
      });
      /********添加多个事件处理********/
      //空格相隔方式
      $(".btn-test").live("mouseout click", function () {
        //显示隐藏div
        $(".container").slideToggle();
      });
      //大括号替代方式
      $(".btn-test").live({
        "mouseout": function () {
          alert("这是mouseout事件!");
        },
        "click": function () {
          $(".container").slideToggle();
        }
      });
      /********删除事件处理********/
      $(".btn-test").die("click");
    });
  </script>
</head>
<body>
  <input type="button" value="按钮" class="btn-test" />
  <div class="container">
  </div>
</body>
</html>

Copy after login

适用Jquery版本

jquery1.9版本以下支持,jquery1.9及其以上版本删除了此方法,jquery1.9以上版本用on()方法来代替。

三、delegate()

简要描述

delegate() 为指定的元素(被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。

使用方式

复制代码 代码如下:
$(selector).delegate(childSelector,event,data,function)

childSelector: 必需项;需要添加事件处理程序的元素,一般为selector的子元素;
event:必需项;添加到元素的一个或多个事件,例如 click,dblclick等;

单事件处理:例如

复制代码 代码如下:
$(selector).delegate(childselector,"click",data,function);

多事件处理:1.利用空格分隔多事件,例如
复制代码 代码如下:
$(selector).delegate(childselector,"click dbclick mouseout",data,function);

2.利用大括号灵活定义多事件,例如
复制代码 代码如下:
$(selector).delegate(childselector,{event1:function, event2:function, ...})

3.空格相隔方式:绑定较为死板,不能给事件单独绑定函数,适合处理多个事件调用同一函数情况;

大括号替代方式:绑定较为灵活,可以给事件单独绑定函数;

data:可选;需要传递的参数;
function:必需;当绑定事件发生时,需要执行的函数;

举例说明

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>jquery中delegate()绑定事件方式</title>
  <style type="text/css">
    .container
    {
      width: 300px;
      height: 300px;
      border: 1px #ccc solid;
      background-color: Green;
    }
    .btn-test
    {
      border: 1px #ccc solid;
      padding: 5px 15px;
      cursor: pointer;
    }
  </style>
  <script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      /***********单元素添加单事件***********/
      //按钮绑定单击事件 实现div的显示隐藏
      $(".header").delegate("#btn-test1", "click", function () {
        $(".container").slideToggle();
      });
      /***********单元素添加多事件***********/
      //空格相隔方式
      $(".header").delegate("#btn-test1", "click mouseout", function () {
        $(".container").slideToggle();
      });
      //大括号替代方式
      $(".header").delegate("#btn-test1", {
        "mouseout": function () {
          alert("这是mouseout事件!");
        },
        "click": function () {
          $(".container").slideToggle();
        }
      });
    });
  </script>
</head>
<body>
  <div class="header">
    <input type="button" value="按钮1" class="btn-test" id="btn-test1" />
    <input type="button" value="按钮2" class="btn-test" id="btn-test2" />
  </div>
  <div class="container">
  </div>
</body>
</html>

Copy after login

适用Jquery版本

jquery1.4.2及其以上版本;

四、on()

简要描述

on() 为指定的元素,添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。使用 on() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。

使用方式

复制代码 代码如下:
$(selector).on(event,childselector,data,function)

event:必需项;添加到元素的一个或多个事件,例如 click,dblclick等;

单事件处理:例如

复制代码 代码如下:
$(selector).on("click",childselector,data,function);

多事件处理:1.利用空格分隔多事件,例如
复制代码 代码如下:
$(selector).on("click dbclick mouseout",childseletor,data,function);

2.利用大括号灵活定义多事件,例如
复制代码 代码如下:
$(selector).on({event1:function, event2:function, ...},childselector);

3.空格相隔方式:绑定较为死板,不能给事件单独绑定函数,适合处理多个事件调用同一函数情况;

大括号替代方式:绑定较为灵活,可以给事件单独绑定函数;

childSelector: 可选;需要添加事件处理程序的元素,一般为selector的子元素;
data:可选;需要传递的参数;
function:必需;当绑定事件发生时,需要执行的函数;

举例说明

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>jquery中on()绑定事件方式</title>
  <style type="text/css">
    .container
    {
      width: 300px;
      height: 300px;
      border: 1px #ccc solid;
      background-color: Green;
    }
    .btn-test
    {
      border: 1px #ccc solid;
      padding: 5px 15px;
      cursor: pointer;
    }
  </style>
  <script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      /*********添加单个事件处理*********/
      $(".header").on("click", ".btn-test", function () {
        //显示隐藏div
        $(".container").slideToggle();
      });
      /********添加多个事件处理********/
      //空格相隔方式
      $(".header").on("mouseout click", ".btn-test", function () {
        //显示隐藏div
        $(".container").slideToggle();
      });
      //大括号替代方式
      $(".header").on({
        "mouseout": function () {
          alert("这是mouseout事件!");
        },
        "click": function () {
          $(".container").slideToggle();
        }
      }, ".btn-test");
      //删除事件
      $(".header").off("click", ".btn-test");
    });
  </script>
</head>
<body>
  <div class="header">
    <input type="button" value="按钮" class="btn-test" />
  </div>
  <div class="container">
  </div>
</body>
</html>

Copy after login

适用Jquery版本

jquery1.7及其以上版本;jquery1.7版本出现之后用于替代bind(),live()绑定事件方式;

五、四种方式的异同和优缺点

相同点:

1.都支持单元素多事件的绑定;空格相隔方式或者大括号替代方式;
2.均是通过事件冒泡方式,将事件传递到document进行事件的响应;

比较和联系:

1.bind()函数只能针对已经存在的元素进行事件的设置;但是live(),on(),delegate()均支持未来新添加元素的事件设置;演示代码如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>jquery中四种方式给未来元素设置事件</title>
  <style type="text/css">
    .container
    {
      width: 300px;
      height: 300px;
      border: 1px #ccc solid;
      background-color: Green;
    }
    .btn-test
    {
      border: 1px #ccc solid;
      padding: 5px 15px;
      cursor: pointer;
    }
  </style>
  <script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      //利用bind()方法,给P标签设置click方法  ======失败 没有任何反应=======
      $(".container p").bind("click", function () {
        alert("bind()添加单击事件成功!");
      });
      //利用live()方法.给P标签设置click方法  =======成功调用方法============
      $(".container p").live("click", function () {
        alert("live()添加单击事件成功!");
      });
      //利用delegate()方法.给P标签设置click方法 =======成功调用方法============
      $(".container").delegate("p", "click", function () {
        //显示隐藏div
        alert("delegate()添加单击事件成功!");
      });
      //利用on()方法.给P标签设置click方法 =======成功调用方法============
      $(".container").on("click", "p", function () {
        //显示隐藏div
        alert("on()添加单击事件成功!");
      });
      //按钮添加P标签
      $(".btn-test").click(function () {
        $(".container").append("<p>这是新增的段落!</p>");
      });
    });
  </script>
</head>
<body>
  <input type="button" class="btn-test" value="添加元素" />
  <div class="container">
  </div>
</body>
</html>

Copy after login

2.bind()函数在jquery1.7版本以前比较受推崇,1.7版本出来之后,官方已经不推荐用bind(),替代函数为on(),这也是1.7版本新添加的函数,同样,可以用来代替live()函数,live()函数在1.9版本已经删除;

3.live()函数和delegate()函数两者类似,但是live()函数在执行速度,灵活性和CSS选择器支持方面较delegate()差些,想了解具体情况,请参考这篇《jQuery中的.bind()、.live()和.delegate()之间区别分析

4.bind()支持Jquery所有版本;live()支持jquery1.8-;delegate()支持jquery1.4.2+;on()支持jquery1.7+;

六、总结

如果项目中引用jquery版本为低版本,推荐用delegate(),高版本jquery可以使用on()来代替,以上仅为个人看法,如有不同想法,欢迎拍砖交流。

更多关于jQuery事件相关内容感兴趣的读者可查看本站专题:《jQuery常见事件用法与技巧总结

希望本文所述对大家jQuery程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to fix 0x87dd0019 Xbox login error How to fix 0x87dd0019 Xbox login error Mar 22, 2024 pm 02:30 PM

This article will guide you to fix the 0x87dd0019 Xbox login error, which causes connection timeout issues when you try to connect to Xbox Live or log in to Xbox One. What is error code 0x87e00019 on Xbox? If you encounter error code 0x87e00019 when installing or updating games on your Xbox console, it means your Xbox hard drive may be low on storage space or nearly full. To solve this problem, you need to free up some storage space. At the same time, you should also check the status of the Xbox Live service, as this error may be due to Xbox server issues. How to fix 0x87dd0019 Xbox login error using these tips

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles