将动态行添加到HTML中

时间:2013-12-01 12:34:58

标签: javascript php html html5 dom

这是经过大量研究后得到的,所以虽然我会分享,

如果我可以更优化它,请告诉我。 此代码在单击添加行时添加新行,并且还动态分配id和名称。

        <script type="text/javascript">
        $(document).ready(function(e) {
        //n:variable for generating dynamic values
        var n=1;
        $("#add").click(function() {    
        n++;

       // converting HTML to JS readable format
       var strVar="";
       strVar += "<tr>";
       strVar += "        <td id=\"day\">Day ";
       strVar += n;
       strVar +=" <\/td>";
       strVar += "        <td><textarea name=\"" ;
       strVar += n;
       strVar +="\"cols=\"50\" rows=\"10\" id=\"" 
       strVar += n;
       strVar +="\"><\/textarea><\/td>";
       strVar += "      <\/tr>";

     $(strVar).insertAfter("#mytable tr:nth-last-child(3)");
             document.getElementById("h").value= n;     
             return false;
             });

      });

   </script> 

HTML

    <table>
    <tr id="test">
      <td id="day">Day 1</td>
      <td><textarea name="1" cols="50" rows="10" id="1"></textarea></td>
    </tr>




  <tr><td>&nbsp;</a></td><td><a href="#" id="add" style="color:#00F">Add another Day</td>   </tr>
  <tr>
    <!-- sending hidden field with the number of fields generated for entering into db using php-->
    <td>&nbsp; <input type="hidden" id="h" value=""/>  </td>
    <td><input type="image" name="button"  src="../images/admin/submit.png" onMouseOver="this.src='../images/admin/submit_hover.png'" onMouseOut="this.src='../images/admin/submit.png'" id="button" value="Add this Item now"></td>
  </tr>
  </table>

1 个答案:

答案 0 :(得分:1)

documentfragment用于创建快速dom节点。

var f=document.createDocumentFragment();
for(var a=0;a<5;a++){
 var field=document.createElement('td');
 field.textContent='field '+a;
 f.appendChild(field);
}
yourTable.appendChild(document.createElement('tr')).appendChild(f);

慢但短。

var tr='<tr><td>field '+['1','2','3','4','5'].join('</td><td>field ')+'</td></tr>';