【发布时间】:2020-06-28 15:56:42
【问题描述】:
我正在尝试将所有城市文本包含在 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