如何将fetch获取的公司网站文本转换为浏览器中可点击的超链接
实现官网字段渲染为可点击超链接的方案
你当前代码直接给companyWebsite节点赋值了纯文本内容,所以无法生成可点击的链接,只需替换官网字段的渲染逻辑即可:
- 删除原有代码中的
companyWebsite.textContent = profile.website;行 - 新增超链接创建逻辑,可按需添加
target="_blank"配置实现新标签页打开,避免跳转离开当前站点
修改后的完整代码如下:
function getCompanyProfile(symbol) { const url = `https://.appspot.com/api/v3/company/profile/${symbol}`; fetch(url) .then((response) => response.json()) .then((data) => { const profile = data.profile; companyTitle.textContent = profile.companyName; // 替换原有官网纯文本渲染逻辑 const websiteLink = document.createElement("a"); websiteLink.href = profile.website; websiteLink.textContent = profile.website; // 可选配置:新标签页打开、添加自定义样式类 websiteLink.target = "_blank"; // websiteLink.classList.add("your-custom-class"); // 先清空原有节点内容再插入超链接 companyWebsite.innerHTML = ""; companyWebsite.appendChild(websiteLink); companyDescription.textContent = profile.description; price.textContent = "Stock Price: $" + profile.price; let profileChangesPercent = Number(profile.changesPercentage); if (profileChangesPercent >= 0) { changesPercentage.classList.add("green"); } else if (profileChangesPercent < 0) { changesPercentage.classList.add("red"); } changesPercentage.textContent = profileChangesPercent.toFixed(2) + "%"; // set logo let img = document.createElement("img"); img.src = profile.image; companyLogo.appendChild(img); console.log(data); }) .catch((err) => { console.warn("Something went wrong.", err.message); }); }
*如果你的companyWebsite本身就是<a>标签,也可以直接给它设置href属性,不需要额外创建新节点:
companyWebsite.href = profile.website; companyWebsite.textContent = profile.website;
内容的提问来源于stack exchange,提问作者Barak David
相关产品推荐
相关产品推荐

