SoFunction
Updated on 2025-02-28

A brief analysis of JS delegate and live

There are two methods in jquery that can be used to bind automatically appended DOM objects. They are live and delegate. In fact, these two methods are a variant of the bind method. When fixing DOM objects, we usually use bind. However, when the DOM objects generated dynamically are powerless to use bind, and live and delegate appear, haha.

Live method, used to bind a certain object (a certain type) and bind a method for them

Copy the codeThe code is as follows:

    //live
            $("td").live("click", function () {
                alert($(this).html());
            });
//The following is also OK
                 alert($(this).html());
           });

Delegate method is used to bind a child object under a certain (certain type) object and bind a method for the child object (delegate the child object and let the child object have a certain method, haha)

Copy the codeThe code is as follows:

 $("#list").delegate("td", "click", function () {
                alert($(this).html());
            });

The following DEMO completion code:

Copy the codeThe code is as follows:

<html lang="en" xmlns="http:///1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="" type="text/javascript"></script>
    <script type="text/html">
        <tr>
            <td>[UserID]</td>
            <td>[UserImg]</td>
            <td>[UserName]</td>
        </tr>
    </script>
    <script type="text/javascript">
var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm'); //i g m refers to the case-sensitive match, global match and multi-line match respectively.

        $(function () {
            //live
            $("#list td").live("click", function () {
                alert($(this).html());
            });

            $("#addFun").click(function () {
                var html = ("listTemplate").innerHTML;
                var source = (reg, function (node, key) { return { 'UserImg': '1', 'UserName': 'zhang', 'UserID': '1' }[key]; });
                $("#list").append(source);
            });

        });
    </script>
</head>
<body>
    <div >
    </div>
    <input type="button" value="click me" />
    <table border="1">
        <tbody>
        </tbody>
    </table>
</body>
</html>