要在网页上动态添加表格,可以使用JavaScript和HTML,以下是一个简单的示例:

1、在HTML文件中创建一个按钮,用于触发添加表格的操作:
<button id="addTableBtn">添加表格</button>
2、编写JavaScript代码,实现点击按钮后动态添加表格的功能:
<script>
// 获取按钮元素
const addTableBtn = document.getElementById('addTableBtn');
// 为按钮添加点击事件监听器
addTableBtn.addEventListener('click', () => {
// 创建表格元素
const table = document.createElement('table');
// 创建表头行
const thead = document.createElement('thead');
const tr = document.createElement('tr');
const th1 = document.createElement('th');
th1.innerText = '列1';
const th2 = document.createElement('th');
th2.innerText = '列2';
tr.appendChild(th1);
tr.appendChild(th2);
thead.appendChild(tr);
table.appendChild(thead);
// 创建表体行
const tbody = document.createElement('tbody');
const trBody = document.createElement('tr');
const td1 = document.createElement('td');
td1.innerText = '数据1';
const td2 = document.createElement('td');
td2.innerText = '数据2';
trBody.appendChild(td1);
trBody.appendChild(td2);
tbody.appendChild(trBody);
table.appendChild(tbody);
// 将表格添加到页面中
document.body.appendChild(table);
});
</script> 这段代码首先获取了按钮元素,并为其添加了点击事件监听器,当点击按钮时,会创建一个新的表格元素,包括表头和表体,表头包含两列,表体包含一行数据,将创建的表格添加到页面中。

【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!
发表回复