亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 JavaScript 生成多個 a 標簽?

如何使用 JavaScript 生成多個 a 標簽?

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);

});


查看完整回答
反對 回復 2023-04-20
?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

A。是的,創建一個循環。你也可以使用順便countries.forEach(()=> ...)說一句。 b. 不要忘記在循環繼續之前附加元素。 C。一個小建議——如果代碼越來越大,將代碼分成具有有意義名稱的小函數。

祝你好運!


查看完整回答
反對 回復 2023-04-20
  • 2 回答
  • 0 關注
  • 254 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號