單擊按鈕透過原生 JavaScript 在 div 元素上顯示陣列項
如需將陣列的元素嵌入 div 中,我們只需遍歷陣列並不斷將元素追加至 div
可像這樣完成:−
示例
const myArray = ["stone","paper","scissors"];
const embedElements = () => {
myArray.forEach(element => {
document.getElementById('result').innerHTML +=
`<div>${element}</div><br />`;
// here result is the id of the div present in the DOM
});
};此程式碼假定我們想要在其中顯示陣列元素的 div 的 ID 為“結果”。
此程式碼的完整形式如下:−
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="result"></div>
<button onclick="embedElements()">Show Data</button>
<script>
{
const myArray = ["stone","paper","scissors"];
function embedElements(){
myArray.forEach(el => {
document.getElementById('result').innerHTML +=`<div>${el}</div><br />`;
// here result is the id of the div present in the dom
});
};
}
</script>
</body>
</html>輸出

單擊按鈕“顯示資料”時,將可見如下內容:−

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP