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

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

使用 JavaScript 將鏈接標簽包裹在文本周圍

使用 JavaScript 將鏈接標簽包裹在文本周圍

catspeake 2023-09-18 10:32:38
鏈接到 CodePen。我試圖將所有城市文本包裝在“位置”列下,并提供指向網站上特定位置頁面的鏈接。因此,劍橋將被包裝在前往劍橋頁面的鏈接標簽中,蒂明斯將被包裝在前往蒂明斯頁面的鏈接標簽中,等等。我一開始只使用兩個鏈接來嘗試使其正常工作。循環訪問位置列中的 td,如果該值等于特定文本,則添加指向它的鏈接。試圖讓它發揮作用。JS/////// Grab the Locations column ///////let col5 = document.querySelectorAll("td:nth-child(5)");// Cities Dataconst cities = [  {    id: 1,    city: 'Cambridge',    link: '/locations/cambridge'  },  {    id: 2,    city: 'Timmins',    link: '/locations/timmins'  }]/////// Link up all td's to location pages ///////// Loop over locations columnfor (let i = 0; i < col5.length; i++) {  // If it matches the specific city, wrap text around link tag linking to specific location  if (col5.innerHTML === cities[0].city) {    // Set Links Info    a.setAttribute("href", cities[0].link);    // Append    col5[i].appendChild(a);  } else if (col5.innerHTML === cities[1].city) {    // Set Links Info    a.setAttribute("href", cities[1].link);    // Append    col5[i].appendChild(a);  }}
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

正如您可能想象的那樣,復制/粘貼/修改每個代碼的代碼cities無論如何都不理想。

您可以考慮使用數組方法,例如forEachfind...

const cities = [

? { id: 1, city: 'Cambridge', link: '/locations/cambridge' },

? { id: 2, city: 'Timmins', link: '/locations/timmins' }

]


// Go through each cell

let col5 = document.querySelectorAll("td:nth-child(5)");

col5.forEach(function(el) {

? // Find the city

? var city = cities.find(function(x) { return x.city == el.innerHTML; });

? if (city) {

? ? // Wrap in a link

? ? el.innerHTML = '<a href="' + city.link + '">' + el.innerHTML + '</a>';

? }

});

<table>

? <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>Cambridge</td></tr>

? <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>Timmins</td></tr>

</table>

(在任何人發表評論之前請注意...我使用function(x) {}而不是x =>因為我仍然需要為 IE11 編寫代碼,它不支持箭頭函數)



查看完整回答
反對 回復 2023-09-18
  • 1 回答
  • 0 關注
  • 110 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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