You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在页面a标签href包含指定关键词时修改其rel属性

解决方案

这个需求完全可以实现,仅需在原有脚本的判断逻辑中加入关键词匹配规则即可,修改后的完整脚本如下:

<script type='text/javascript'>
function myFunction() {
  // 在这里配置需要匹配的联盟链接关键词,后续增减直接改这个数组即可
  const affiliateKeywords = ['abc', 'qrs', 'xyz'];
  const links = document.getElementsByTagName("a");
  for (let i = 0; i < links.length; i++) {
    const currentHref = links[i].href;
    // 检测当前链接href是否包含任意一个联盟关键词
    const isAffiliateLink = affiliateKeywords.some(keyword => currentHref.includes(keyword));
    if (isAffiliateLink) {
      links[i].rel = "sponsored";
      links[i].target = "_blank";
      links[i].title = "Click to open in new window";
    }
  }
}
mft=setTimeout("myFunction()",0);
function LoadEvent(func){
  var oldonload = window.onload;
  if (typeof window.onload != 'function'){
    window.onload = func;
  } else {
    window.onload = function()
    {
      if(oldonload)
      {oldonload();}
      func();
    }
  }
}
LoadEvent(function(){
  myFunction();
});
</script>

调整说明

  • 新增了affiliateKeywords配置数组,你后续如果需要新增或者删除需要识别的联盟链接关键词,直接修改这个数组里的内容即可,不需要改动其他逻辑
  • 替换了原有的外站链接判断规则,现在只有链接地址包含数组内的指定关键词时,才会自动加上赞助属性、新窗口打开规则和提示文字
  • 如果你还需要额外保证只处理非本站的联盟链接,可以把判断条件改成if (isAffiliateLink && location.hostname != links[i].hostname)即可,避免误处理本站包含关键词的链接

内容的提问来源于stack exchange,提问作者Justmac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 17:06:00