【问题标题】:Wrapping a link tag around text with JavaScript使用 JavaScript 将链接标签包裹在文本周围
【发布时间】:2020-06-28 15:56:42
【问题描述】:

Link to CodePen.

我正在尝试将所有城市文本包含在 Location 列下,并带有指向其在网站上的特定位置页面的链接。所以剑桥会被包裹在一个链接标签中去剑桥页面,蒂明斯将被包裹在一个链接标签中去蒂明斯页面,等等。

我一开始只有两个链接来尝试使其正常工作。循环遍历 location 列中的 td,如果值等于特定文本,则添加指向它的链接。试图让它工作。

JS

/////// Grab the Locations column ///////

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

// Cities Data

const 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 column
for (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);
  }
}

【问题讨论】:

  • 您应该尝试在您的问题中添加minimal reproducible example 示例,而不是链接到代码笔。它可以帮助您缩小问题范围,也可以帮助我们。

标签: javascript html loops if-statement


【解决方案1】:

正如您可能想象的那样,复制/粘贴/修改每个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 =&gt;,因为我仍然需要为IE11编码,doesn't support arrow functions

【讨论】:

  • 非常感谢!我同意,这段代码不那么冗长。
  • 不客气 - 祝你项目的其余部分好运。我注意到你在你的 codepen 中使用 jQuery,所以代码可能会继续改进......但由于你没有在你的问题或标签中说明它,我没有走那条路
猜你喜欢
  • 2011-07-06
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多