JS delegate and live analysis

  • 2020-03-30 00:59:10
  • OfStack

There are two methods can be used for binding in jquery automatically append the DOM object, they are live and delegate, in fact, these two methods is a variant of the bind method on fixed DOM object, we usually use the bind is ok, and the DOM object generated by the dynamic object, use the bind is powerless, then played live and delegate, ha ha.

A live method that binds certain (class) objects and binds methods for them


        //live
            $("td").live("click", function () {
                alert($(this).html());
            });
           //The following is also possible & NBSP;                   $("#list td").live("click", function () {
                 alert($(this).html()); 
           });

The delegate method is used to bind the child object under a certain object, and bind the method for the child object (delegate the child object, let the child object have a certain method, hehe).


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

The complete code of the following DEMO:


<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="jquery.js" type="text/javascript"></script>
    <script id="listTemplate" 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 is for specifying case-sensitive matches, global matches, and multi-line matches, respectively.
        $(function () {
            //live
            $("#list td").live("click", function () {
                alert($(this).html());
            });
            $("#addFun").click(function () {
                var html = document.getElementById("listTemplate").innerHTML;
                var source = html.replace(reg, function (node, key) { return { 'UserImg': '1', 'UserName': 'zhang', 'UserID': '1' }[key]; });
                $("#list").append(source);
            });
        });
    </script>
</head>
<body>
    <div id="comment_ul_2">
    </div>
    <input type="button" id="addFun" value="click me" />
    <table id="list" border="1">
        <tbody>
        </tbody>
    </table>
</body>
</html>


Related articles: