简体   繁体   English

如何在 Javascript 中插入 HTML 表格?

[英]How to insert an HTML table in Javascript?

I need to write a JS function called addMultiTable(rows, cols) that will create a multiplication table with 4 rows and 8 columns, and append it after the header: <h1>Multiplication Table</h1> .我需要编写一个名为addMultiTable(rows, cols)的 JS 函数,该函数将创建一个 4 行 8 列的乘法表,并将其附加在标题之后: <h1>Multiplication Table</h1>

 <!DOCTYPE html> <html lang="en"> <head> <title>Table</title> </head> <body> <h1>Multiplication Table</h1> </body> </html>

This should work for you, remember there are a few ways to solve this problem这应该对你有用,记住有几种方法可以解决这个问题

function addMultiTable(rows, cols) {
var table = document.createElement("table"),
    elem = document.getElementsByTagName("h1")[0],
    i = 1,
    j = 1,
    val = 0;

for( i; i <= rows; i++ ) {
    var row = document.createElement("tr");

    for( j; j <= cols; j++) {
        var col = document.createElement("td");
        val = i * j;
        col.innerHTML = val;
        row.appendChild(col);
    }
    j = 1;
    table.appendChild(row);
}
elem.parentNode.insertBefore(table,elem.nextSibling);
}
addMultiTable(4,8);

 function addMultiTable(rows, cols) { var myHeader = document.getElementsByTagName("h1")[0]; var table = document.createElement("table"); for(i=0; i < rows; i++ ) { var row = document.createElement("tr"); table.appendChild(row); for (j = 0; j < cols; j++) { var cell = document.createElement("td"); cell.innerHTML = (i+1)*(j+1);//value inside cells row.appendChild(cell); } table.appendChild(row); } myHeader.appendChild(table); }

Use jQuery .append() function to append the table to the div.使用 jQuery .append() 函数将表格附加到 div。

You can find the demo of the .append() in https://jsfiddle.net/stktjo67/您可以在https://jsfiddle.net/stktjo67/找到 .append() 的演示

And Here is the documentation link for .append() http://api.jquery.com/append/这是 .append() http://api.jquery.com/append/的文档链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM