如何用JavaScript检测论坛用户Profile链接有效性并设置差异化样式?
解决方法
先筛选出论坛里符合用户Profile格式的链接,再逐个检测有效性,最后设置对应文字颜色:
1. 匹配目标链接
这类链接都是https://xxx-xxx.domain.com/的格式,用正则表达式筛选页面中符合规则的<a>标签:
// 匹配论坛用户Profile链接的正则 const profileLinkRegex = /^https:\/\/.*-.*\.domain\.com\/$/; // 筛选出所有符合规则的链接 const profileLinks = Array.from(document.querySelectorAll('a')).filter(link => { return profileLinkRegex.test(link.href); });
2. 检测链接有效性并设置颜色
用fetch发送HEAD请求(仅获取响应头,比GET请求更轻量),根据响应状态码判断:
- 状态码在200-399区间:链接有效,文字设为蓝色
- 状态码为404:链接无效(未创建Profile),文字设为红色
// 遍历处理每个目标链接 profileLinks.forEach(link => { fetch(link.href, { method: 'HEAD' }) .then(response => { if (response.ok) { link.style.color = 'blue'; } else if (response.status === 404) { link.style.color = 'red'; } }) .catch(error => { // 请求失败(比如跨域限制)时,默认标记为红色 console.error(`检测链接 ${link.href} 失败:`, error); link.style.color = 'red'; }); });
额外提示
把代码放在页面加载完成的事件里,确保所有链接都已渲染:
window.addEventListener('load', () => { // 上述匹配和检测代码放在这里 });
内容的提问来源于stack exchange,提问作者John E
相关产品推荐
相关产品推荐

