猿问

如何使用 JavaScript 生成多个 a 标签?

我想创建多个a标签来填充一个div. 用 HTML 编写此代码会占用很多行,而使用 JavaScript 脚本会使事情变得更容易。不幸的是,我仍在学习它,并且正在寻求帮助。


下面是我想要使用 JavaScript 生成的 HTML 代码,在里面div id="countries"


<div class="countries">

  <div id="Denmark">

    <h4>Denmark</h4>

<!-- number of links is variable to each country -->

    <a href="https://www.example.com">Link1</a>

    <a href="https://www.example2.com">Link2</a>

  </div>

</div>

一些JS代码


let countrySelect = document.getElementsByClassName('countries');


let links = ["https://www.example1.com", "https://www.example2.com", "https://www.example3.com", "https://www.example4.com", "https://www.example5.com", "https://www.example6.com", "https://www.example7.com", "https://www.example7.com"];


// make an array of countries

let countries = ["Denmark", "Spain", "Italy", "Slovenia", "Malta", "Hungary", "Austria", "Czech Republic"];


// make a div

let makeDiv = document.createElement("div");

// add an ID to div just created

makeDiv.setAttribute('id', 'country');

// make an A tag

let tag = document.createElement("a");

tag.setAttribute('href', links[1]); // multiple links needed...integrate in a loop?


// make a loop to create multiple country divs

for (let index = 0; index < countries.length; index++) {

  // insert all the elements in the loop

}


aluckdog
浏览 213回答 2
2回答

森林海

您需要创建元素并在循环中a设置其和文本。hrefcountries.forEach(country => {&nbsp; &nbsp; let makeDiv = document.createElement("div");&nbsp; &nbsp; makeDiv.id = country;&nbsp; &nbsp; let h4 = document.createElement("h4");&nbsp; &nbsp; h4.innerText = country;&nbsp; &nbsp; makeDiv.appendChild(h4);&nbsp; &nbsp; links.forEach((link, i) => {&nbsp; &nbsp; &nbsp; &nbsp; let tag = document.createElement('a');&nbsp; &nbsp; &nbsp; &nbsp; tag.href = link;&nbsp; &nbsp; &nbsp; &nbsp; tag.innerText = `Link${i+1}`;&nbsp; &nbsp; &nbsp; &nbsp; makeDiv.appendChild(tag);&nbsp; &nbsp; });&nbsp; &nbsp; countrySelect[0].appendChild(makeDiv);});

智慧大石

A。是的,创建一个循环。你也可以使用顺便countries.forEach(()=> ...)说一句。&nbsp;b.&nbsp;不要忘记在循环继续之前附加元素。&nbsp;C。一个小建议——如果代码越来越大,将代码分成具有有意义名称的小函数。祝你好运!
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答