Several methods of dynamic generating html elements in jQuery

Posted by Hellomonkey on Mon, 30 Mar 2020 19:45:42 +0200

In general, html elements can be created dynamically in the following ways:

1. Syntax for creating elements using jQuery
2. Store the dynamic content in the array, and then traverse the array to dynamically create html elements
3. Use template

1. Use jQuery to dynamically create elements and append them to jQuery objects.

<meta http-equiv="Content-Type"content="text/html; charset=utf-8"/>

  <title></title>

  <script src="Scripts/jquery-1.10.2.js"></script>

  <script type="text/javascript">

    $(function() {

      $('<input />', {

        id:'cbx',

        name:'cbx',

        type:'checkbox',

        checked:'checked',

        click:function() {

          alert("Order me.~~");

        }

      }).appendTo($('#wrap'));

    });

  </script>

</head>

<body>

  <div id="wrap"></div>

</body>

The operation effect is as follows:

2. First put the content into the array, and then traverse the array to splice it into html

<head>

<meta http-equiv="Content-Type"content="text/html; charset=utf-8"/>

  <title></title>

  <script src="Scripts/jquery-1.10.2.js"></script>

  <style type="text/css">

    table {

      border: solid 1px red;

      border-collapse: collapse;

    }

    td {

      border: solid 1px red;

    }

  </style>

  <script type="text/javascript">

    $(function() {

      vardata = ["a","b","c","d"];

      varhtml = '';

      for(vari = 0; i < data.length; i ++) {

        html += "<td>"+ data[i] + "</td>";

      }

      $("#row").append(html);

    });

  </script>

</head>

<body>

  <table>

    <tr id="row"></tr>

  </table>

</body>

</html>

The operation effect is as follows:

3. Use template to generate html

<meta http-equiv="Content-Type"content="text/html; charset=utf-8"/>

  <title></title>

  <script src="Scripts/jquery-1.10.2.js"></script>

  <script type="text/javascript">

    $(function() {

      vara = buildHTML("a","I was generated from a template", {

        id:"myLink",

        href:"http://www.baidu.com"

      });

      $('#wrap1').append(a);

      varinput = buildHTML("input", {

        id:"myInput",

        type:"text",

        value:"I was also generated by the template~~"

      });  

      $('#wrap2').append(input);

    });

    buildHTML = function(tag, html, attrs) {

      // you can skip html param

      if(typeof(html) != 'string') {

        attrs = html;

        html = null;

      }

      varh = '<'+ tag;

      for(attr inattrs) {

        if(attrs[attr] === false)continue;

        h += ' ' + attr + '="'+ attrs[attr] + '"';

      }

      returnh += html ? ">"+ html + "</"+ tag + ">": "/>";

    };

  </script>

</head>

<body>
  <div id="wrap1"></div>

  <div id="wrap2"></div>
</body>

The operation effect is as follows:

Topics: JQuery Javascript