SoFunction
Updated on 2025-03-03

Analysis of JS method to dynamically generate html table table

This article describes the method of JS to dynamically generate html table tables. Share it for your reference, as follows:

When I was browsing on the forum, I saw someone asking how to generate html forms dynamically. I replied and found that many friends asked them - it seems that many people still don’t know what they don’t know, so I decided to write a blog to save thousands of friends from the fire and water (mdzz)

First we need to have the following code in the html:

<table>
  <tbody >
  </tbody>
</table>

If you want to add other things to the table, you can add them at will (such as adding a header, etc.), you just need to know that all the contents generated by js will be in the tbody later.

Then you need the following js to dynamically generate html:

function creatTable(data){
 //The parameters of this function can be transmitted from the background or from anywhere else //Here I assume this data is a string array of length 5. I want to put it in a row of the table and divide it into five columns var tableData="&lt;tr&gt;"
 // Dynamically add 5 tds, and assign five values ​​of the data array to each td for(var i=0;i&lt;;i++){
  tableData+="&lt;td&gt;"+data[i]+"&lt;/td&gt;"
 }
 tableData+="&lt;/tr&gt;"
 //Now tableData has been generated, assign it to the above tbody $("#tbody1").html(tableData)
}

The tableData above can be added to the html language at will. For example, let's set the width of the tr andvar tableData=""Change to:

var tableData="<tr style='width:300px'>"

It should be noted that we have used double quotes when assigning values ​​to tableData, so we must use single quotes when setting style, otherwise an error will be reported. Everyone should know this, so I won’t say much.

Finally, call the function written on the page to dynamically add data to the table. Or we can also let the page automatically add data to the table when it is loaded:

&lt;script type="text/javascript"&gt;
 ()=function ()
 {
  //Copy the content of the above creatTable function in this }
&lt;/script&gt;

For more information about JavaScript, readers who are interested in reading this site's special topic:Complete collection of JavaScript table operation techniques》、《Summary of JavaScript DOM skills》、《Summary of JavaScript array operation skills》、《JavaScript traversal algorithm and skills summary》、《Summary of JavaScript mathematical operations usage》、《Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript search algorithm skills"and"Summary of JavaScript Errors and Debugging Skills

I hope this article will be helpful to everyone's JavaScript programming.