单击按钮通过原生 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