因此,我必须根据HTML代码生成多个表。我可以使用纯JavaScript代码生成多个表,但是分配ID和获取其值太困难了。正如我写的javascript函数generate_table因此,我从该HTML表创建了一个示例HTML表,该方法如何再次生成同一表(多次)。我为表TD和TR写了太多的JavaScript代码。如何减少该代码。我有很多表,我想重新生成特定的表,所以我不能使用<table>
标签。有什么提示吗?代码示例?
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName('body')[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement('table');
var tblBody = document.createElement('tbody');
// creating all cells
for (var i = 0; i < 1; i++) {
var seqnumber = 1;
var seq = +1;
// creates a table row
var row2 = document.createElement('tr');
//====== table first row data =======//
var seq = document.createElement('td');
var seqText = document.createTextNode('Seq');
var l = document.createElement('td');
var seqText1 = document.createElement('input');
//===== seq generator =====//
seq.appendChild(seqText);
row2.appendChild(seq);
l.appendChild(seqText1);
row2.appendChild(l);
// add the row to the end of the table body
tblBody.appendChild(row2);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute('border', '2');
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<h3> TABLE FROM JAVA SCRIPT</h3>
<input type="button" value="Generate a table." onclick="generate_table()" />
<h3> TABLE FROM HTML</h3>
<table id="table6">
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
<input type="button" value="Generate same table from HTML." />
JSfiddle链接:-> https://jsfiddle.net/shreekantbatale2/evqsuxm8/5/
您每次想要新的<template>
时都可以使用<table>
元素来生成新的HTML>
const button = document.querySelector('.js-create-table'); const template = document.createElement('template'); template.innerHTML = ` <table> <tr> <th colspan="2">Aggregator</th> </tr> <tr> <th> Column Name </th> <th> Function </th> </tr> <tr> <td> <input> </td> <td> <input> </td> </tr> </table> `; function generateTable() { const table = template.content.cloneNode(true); document.body.append(table); } button.addEventListener('click', generateTable);
<button class="js-create-table">Create table</button>
我了解的是您要添加模板表。这是使用jQuery的简单方法