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

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

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 () {

The complete code of the following DEMO:

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <meta charset="utf-8" />
    <script src="jquery.js" type="text/javascript"></script>
    <script id="listTemplate" type="text/html">
    <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 () {
            $("#list td").live("click", function () {
            $("#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]; });
    <div id="comment_ul_2">
    <input type="button" id="addFun" value="click me" />
    <table id="list" border="1">

Related articles: