新聞中心
在JavaScript中,可以使用DOM(文檔對象模型)操作向HTML中插入控件,以下是一個簡單的示例:

1、創(chuàng)建一個HTML文件,添加一個 2、接下來,創(chuàng)建一個名為 這個示例中,我們首先獲取了頁面中的
script.js的JavaScript文件,編寫以下代碼:
// 獲取容器元素
const container = document.getElementById('container');
// 創(chuàng)建一個新的標題元素
const title = document.createElement('h1');
title.textContent = '這是一個標題';
container.appendChild(title);
// 創(chuàng)建一個新的表格元素
const table = document.createElement('table');
container.appendChild(table);
// 創(chuàng)建表頭
const thead = document.createElement('thead');
table.appendChild(thead);
// 創(chuàng)建表頭行
const tr = document.createElement('tr');
thead.appendChild(tr);
// 創(chuàng)建表頭單元格并設(shè)置內(nèi)容
const th1 = document.createElement('th');
th1.textContent = '列1';
tr.appendChild(th1);
const th2 = document.createElement('th');
th2.textContent = '列2';
tr.appendChild(th2);
// 創(chuàng)建表體
const tbody = document.createElement('tbody');
table.appendChild(tbody);
// 創(chuàng)建表體行
const tr1 = document.createElement('tr');
tbody.appendChild(tr1);
// 創(chuàng)建表體單元格并設(shè)置內(nèi)容
const td1 = document.createElement('td');
td1.textContent = '數(shù)據(jù)1';
tr1.appendChild(td1);
const td2 = document.createElement('td');
td2.textContent = '數(shù)據(jù)2';
tr1.appendChild(td2);
標題名稱:js如何向html中插入控件
分享鏈接:http://fisionsoft.com.cn/article/dpsscog.html


咨詢
建站咨詢
