Home Web Front-end JS Tutorial Detailed explanation of Jquery delegate(),bind(),live(),on() binding event methods

Detailed explanation of Jquery delegate(),bind(),live(),on() binding event methods

Jun 26, 2017 am 10:02 AM
bind jquery live binding

Preface

Since projects often use jquery to add or delete dom elements, it will involve the binding event method of dom elements. Let’s briefly summarize the differences between bind, live, delegate, and on. , for future reference, and I hope this article can help gardeners 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.

bind()

Brief description

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

##How to use

 $(selector).bind(event,data,function)

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

Single event processing: For example, $(selector).bind("click",data,function);

Multi-event processing: 1. Use spaces to separate multiple events, such as $(selector).bind("click dbclick mouseout",data,function);

##                                                                       duct in in , event2:function, ...})## ## 3. Space separation method: Binding is relatively rigid and cannot bind separate functions to events. It is suitable for processing multiple events. Calling the same function;

dataOptional; parameters that need to be passed;

#  functionRequired; when bound Function that needs to be executed when a certain event occurs;

##for example

<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
View Code

#Applicable Jquery version

# Applicable to all versions, but according to the official website, since jquery1.7 version, the bind() function It is recommended to use on() instead.
live()

Brief description

 

live()

To the current or future matching element Add one or more event handlers;

Usage

 $(selector).live(event,data,function)

## Event:

Required; one or more items added to the element single event, such as click, dblclick, etc.; Single event processing: for example

$(selector).live ("click",data,function);# Multi-event processing: 1. Use spaces to separate multiple events Events, such as

$(selector).live("click dbclick mouseout",data,function);

##                                                      2. Use braces to flexibly define multiple events, such as

$(selector).live({event1:function, event2:function, ...}) ## 3. There is a way to separate the space: binding is more rigid, cannot bind functions alone, suitable for processing multiple events call 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:必需;当绑定事件发生时,需要执行的函数;

举例说明

<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

View Code

适用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

View Code

适用Jquery版本

 jque #ry1.4.2# and above; on() Brief description

 on()

For the specified element, add One or more event handlers and specifies functions to run when these events occur. Event handlers using the on() method work on current or future elements (such as new elements created by a script). Usage

## $(selector ).on(event,childselector,data,function)

## event:

Required; one or more events added to the element, such as click, dblclick, etc.; ##    Single event processing: for example $(selector).on("click",childselector,data,function);

Multi-event processing: 1. Use spaces to separate multiple events, such as

$(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


View Code

适用Jquery版本

 jquery1.7## and above; after jquery1.7 version appears, is used to replace bind (), live() binding event method; #Similarities, differences, advantages and disadvantages of the four methods

##Same point:

 1. Both support the binding of single elements and multiple events; spaces Separation method or brace replacement method;

## 2. All events are passed to the document for event response through event bubbling;

比较和联系:

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. The bind() function was relatively popular before jquery version 1.7. After version 1.7 came out, bind() is no longer officially recommended, and the alternative function is on(). This is also The newly added functions in version 1.7 can also be

## Used to replace the live() function, which has been deleted in version 1.9;

#3. The live() function is similar to the delegate() function, but the live() function has better execution speed, flexibility andCSS selectorThe support is worse than delegate()

4.bind() supports all versions of Jquery; live() supports jquery1.8-; delegate() supports jquery1.4.2+; on() supports jquery1.7+; # ##Summary

 

If the jquery version referenced in the project is a lower version, it is recommended to use delegate(), higher versions of jquery can use on() instead. The above is just my personal opinion. If you have different ideas, please feel free to share them.

The above is the detailed content of Detailed explanation of Jquery delegate(),bind(),live(),on() binding event methods. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? Mar 21, 2024 pm 10:11 PM

In today's era of information explosion, the construction of personal brand and corporate image has become increasingly important. As the leading fashion life sharing platform in China, Xiaohongshu has attracted a large number of user attention and participation. For those users who want to expand their influence and improve the efficiency of content dissemination, binding sub-accounts has become an effective means. So, how does Xiaohongshu bind a sub-account? How to check whether the account is normal? This article will answer these questions for you in detail. 1. How to bind a sub-account on Xiaohongshu? 1. Log in to your main account: First, you need to log in to your Xiaohongshu main account. 2. Open the settings menu: click &quot;Me&quot; in the upper right corner, and then select &quot;Settings&quot;. 3. Enter account management: In the settings menu, find the &quot;Account Management&quot; or &quot;Account Assistant&quot; option and click

Steps and methods to bind Douyin in Toutiao Steps and methods to bind Douyin in Toutiao Mar 22, 2024 pm 05:56 PM

1. Open Toutiao. 2. Click My in the lower right corner. 3. Click [System Settings]. 4. Click [Account and Privacy Settings]. 5. Click the button on the right side of [Douyin] to bind Douyin.

How to bind the Cainiao app to Pinduoduo? How to add the Cainiao Wrap to Pinduoduo platform? How to bind the Cainiao app to Pinduoduo? How to add the Cainiao Wrap to Pinduoduo platform? Mar 19, 2024 pm 02:30 PM

The Cainiao app is a platform that can provide you with various logistics information. The functions here are very powerful and easy to use. If you have any logistics-related problems, they can be solved here. Anyway, it can bring you a The one-stop service can solve everything in time. Checking the express delivery, picking up the express delivery, sending the express delivery, etc. are all without any problems. We have cooperated with various platforms and all the information can be queried. However, sometimes It will happen that the goods purchased on Pinduoduo cannot display the logistics information. In fact, you need to manually bind Pinduoduo to achieve this. The specific methods have been sorted out below, and everyone can take a look. . How to bind Cainiao to Pinduoduo account: 1. Open Cainiao APP and go to the main page

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 bind the Cainiao APP to Pinduoduo How to bind the Cainiao APP to Pinduoduo How to bind the Cainiao APP to Pinduoduo How to bind the Cainiao APP to Pinduoduo Mar 19, 2024 pm 05:16 PM

Do you know how to bind Pinduoduo when using Cainiao Wrap? The official version of Cainiao Wrap App does not automatically synchronize some Pinduoduo’s logistics information on this platform. All we need to do is You can copy the order number or check your mobile phone to see if there is any express delivery information. Of course, these all need to be completed manually. If you want to know more, come and take a look with the editor. How to bind the Cainiao APP to Pinduoduo 1. Open the Cainiao APP and click &quot;Package Guide&quot; in the upper left corner of the main page. 2. In the interface, there are many shopping websites, and accounts can be bound. 3. Click to import other e-commerce platforms. 4. User authorization: Click Pinduoduo to go to the interface

How to bind the Xiaomi car app to the charging pile device How to bind the Xiaomi car app to the charging pile device Apr 01, 2024 pm 06:52 PM

The latest Mi su7 model car launched by Xiaomi has dominated various hot search lists. Many users who happen to want to buy a car have chosen Xiaomi su7 model car for purchase. So how do you use your Xiaomi car app to bind the car after picking up the car? If you decide to use a home charging pile for charging, this tutorial guide will give you a detailed introduction, I hope it can help you. First, we open the Xiaomi mobile app, click the My button in the lower right corner, and then in the My interface, you can see the option of home charging pile. After entering the page to bind the charging pile, click the scan code button below and scan the QR code on the charging pile. The QR code can be used to bind the charging pile to the app.

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

See all articles