在JavaScript中,可以使用DOM(文档对象模型)操作向HTML中插入控件,以下是一个简单的示例:

1、创建一个HTML文件,添加一个 2、接下来,创建一个名为 这个示例中,我们首先获取了页面中的
script.js的JavaScript文件,编写以下代码:
// 获取容器元素
const container = document.getElementById('container');
// 创建一个新的标题元素
const title = document.createElement('h1');
title.textContent = '这是一个标题';
container.appendChild(title);
// 创建一个新的表格元素
const table = document.createElement('table');
container.appendChild(table);
// 创建表头
const thead = document.createElement('thead');
table.appendChild(thead);
// 创建表头行
const tr = document.createElement('tr');
thead.appendChild(tr);
// 创建表头单元格并设置内容
const th1 = document.createElement('th');
th1.textContent = '列1';
tr.appendChild(th1);
const th2 = document.createElement('th');
th2.textContent = '列2';
tr.appendChild(th2);
// 创建表体
const tbody = document.createElement('tbody');
table.appendChild(tbody);
// 创建表体行
const tr1 = document.createElement('tr');
tbody.appendChild(tr1);
// 创建表体单元格并设置内容
const td1 = document.createElement('td');
td1.textContent = '数据1';
tr1.appendChild(td1);
const td2 = document.createElement('td');
td2.textContent = '数据2';
tr1.appendChild(td2);
文章名称:js如何向html中插入控件
文章地址:http://www.jxjierui.cn/article/dpsscog.html


咨询
建站咨询
