在 JavaScript 中,创建表格需要:1. 创建 元素;2. 使用 和 创建表头;3. 使用 和 创建表体;4. 使用 创建单元格;5. 设置边框和间距。
如何在 JavaScript 中创建表格
在 JavaScript 中,可以通过创建
元素来创建表格。
步骤:
创建表头
使用
元素创建表头,包含表格的列标题。在 内使用 元素创建行,并在其中使用 元素创建列标题。创建表体
使用 元素创建表体,包含表格的数据。在 内使用 元素创建行,并在其中使用 元素创建单元格。
设置边框和间距
使用 border 和 cellspacing 属性来设置表格的边框和单元格之间的间距。
示例代码:
@@######@@
以上代码会在页面中创建如下表格:
列标题 1 列标题 2 列标题 3行 1,列 1行 1,列 2行 1,列 3行 2,列 1行 2,列 2行 2,列 3行 3,列 1行 3,列 2行 3,列 3
// 创建一个 3 行 3 列的表格const table = document.createElement("table");table.setAttribute("border", "1");table.setAttribute("cellspacing", "0");// 创建表头const thead = document.createElement("thead");const trHead = document.createElement("tr");const th1 = document.createElement("th");th1.innerText = "列标题 1";const th2 = document.createElement("th");th2.innerText = "列标题 2";const th3 = document.createElement("th");th3.innerText = "列标题 3";trHead.appendChild(th1);trHead.appendChild(th2);trHead.appendChild(th3);thead.appendChild(trHead);// 创建表体const tbody = document.createElement("tbody");for (let i = 1; i < 4; i++) { const trBody = document.createElement("tr"); for (let j = 1; j < 4; j++) { const td = document.createElement("td"); td.innerText = `行 ${i},列 ${j}`; trBody.appendChild(td); } tbody.appendChild(trBody);}// 将表头和表体添加到表格中table.appendChild(thead);table.appendChild(tbody);// 将表格添加到页面中document.body.appendChild(table);
登录后复制
以上就是js如何制作table的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2665790.html