如何为数组的每个值创建一个 h1 元素?

假设,假设我有一个名为“fruits”的数组,其中包含不同的水果。看起来像这样的东西:


var fruits = ["bannanna", "apple", "orange", "grapes"]


我想用数组中的每个名称创建一个 h1 元素。我该怎么做呢?


回首忆惘然
浏览 111回答 3
3回答

不负相思意

循环项目,并使用insertAdjacentHTML将项目添加到正文或您想要添加的任何位置。var fruits = ["bannanna", "apple", "orange", "grapes"]fruits.forEach(item => document.body.insertAdjacentHTML('beforeend', `<h1>${item}</h1>`))

偶然的你

你可以通过 forEach 来做到这一点。<div id="generate-h1"></div>var fruits = ["bannanna", "apple", "orange", "grapes"]// Create any HTML Element to put H1 Tags into this HTML Tagvar main = document.createElement('main');// Create H1 items for each fruits// Append it to the main Tag or whatever you have.fruits.forEach(function (fruits) {&nbsp; &nbsp; var headline = document.createElement('h1');&nbsp; &nbsp; headline.textContent = fruits;&nbsp; &nbsp; main.appendChild(headline);});// Inject into the DOMvar app = document.querySelector('#generate-h1');app.appendChild(main);

狐的传说

好吧,试试这个,我相信这会起作用:&nbsp; &nbsp; <!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <title>Try This</title>&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; <h1 id="fruit"></h1>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; var fruits = ["bannanna", "apple", "orange", "grapes"];&nbsp; &nbsp; &nbsp; var text = "";&nbsp; &nbsp; &nbsp; var i;&nbsp; &nbsp; &nbsp; for (i = 0; i < fruits.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; text += fruits[i] + "<br>";&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; document.getElementById("fruit").innerHTML = text;&nbsp; &nbsp; </script>&nbsp; </body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5