如何仅在首页运行指定JavaScript脚本?
解决脚本仅在首页运行的问题
你的判断条件无效是因为几乎所有URL都包含'/',所以indexOf('/') != -1会在所有页面都返回true。要精准识别首页,你可以用以下几种可靠的判断方式:
方法1:判断路径是否为根路径(推荐)
直接检查当前页面的路径是否是根目录/,这是最通用的方式:
<script> // 仅在首页(路径为/)执行 if (window.location.pathname === '/') { let changelink = document.querySelector('#app > div.boxes.cf > a'); // 先判断元素是否存在,避免报错 if (changelink) { changelink.outerHTML = '<a href="#contact">contact us</a>'; } } </script>
方法2:兼容带index.html的首页
如果你的首页URL是https://yourdomain.com/index.html,可以扩展判断条件:
<script> const isHomePage = window.location.pathname === '/' || window.location.pathname === '/index.html'; if (isHomePage) { let changelink = document.querySelector('#app > div.boxes.cf > a'); if (changelink) { changelink.outerHTML = '<a href="#contact">contact us</a>'; } } </script>
方法3:匹配完整首页URL(不推荐,硬编码域名)
如果需要严格匹配完整的首页URL,可以直接写死域名,但这种方式不够灵活,域名变更后需要修改代码:
<script> if (window.location.href === 'https://yourdomain.com/') { let changelink = document.querySelector('#app > div.boxes.cf > a'); if (changelink) { changelink.outerHTML = '<a href="#contact">contact us</a>'; } } </script>
额外提示
加上if (changelink)的判断是为了避免首页元素不存在时抛出错误,提升脚本的健壮性。
内容的提问来源于stack exchange,提问作者Jon Zolmaan-Poyatos
相关产品推荐
相关产品推荐

