aluckdog
2023-04-20 10:48:36
我想創建多個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 countrieslet countries = ["Denmark", "Spain", "Italy", "Slovenia", "Malta", "Hungary", "Austria", "Czech Republic"];// make a divlet makeDiv = document.createElement("div");// add an ID to div just createdmakeDiv.setAttribute('id', 'country');// make an A taglet tag = document.createElement("a");tag.setAttribute('href', links[1]); // multiple links needed...integrate in a loop?// make a loop to create multiple country divsfor (let index = 0; index < countries.length; index++) { // insert all the elements in the loop}
2 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
您需要創建元素并在循環中a設置其和文本。href
countries.forEach(country => {
let makeDiv = document.createElement("div");
makeDiv.id = country;
let h4 = document.createElement("h4");
h4.innerText = country;
makeDiv.appendChild(h4);
links.forEach((link, i) => {
let tag = document.createElement('a');
tag.href = link;
tag.innerText = `Link${i+1}`;
makeDiv.appendChild(tag);
});
countrySelect[0].appendChild(makeDiv);
});

智慧大石
TA貢獻1946條經驗 獲得超3個贊
A。是的,創建一個循環。你也可以使用順便countries.forEach(()=> ...)
說一句。 b. 不要忘記在循環繼續之前附加元素。 C。一個小建議——如果代碼越來越大,將代碼分成具有有意義名稱的小函數。
祝你好運!
添加回答
舉報
0/150
提交
取消