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

如何避免window.location.href跳转后查找DOM元素报错?

解决页面跳转后脚本报错的问题

你遇到的错误是因为同一个script.js被同时引入了index.html和second.html,但second.html中不存在submitBtn元素,导致document.getElementById('submitBtn')返回null,调用addEventListener时触发TypeError。以下是几种实用的解决方式:

方法一:先检查元素是否存在再绑定事件

在脚本中先判断目标元素是否存在,只有存在时才执行事件绑定逻辑,避免对null调用方法:

const submitBtn = document.getElementById('submitBtn');
// 仅当元素存在时绑定事件
if (submitBtn) {
  submitBtn.addEventListener('click', function(e) {
    e.preventDefault();
    window.location.href = 'another_file.html';
  });
}

方法二:根据当前页面区分执行逻辑

通过判断当前页面的特征,只在目标页面(index.html)执行绑定逻辑:

方式1:通过URL判断

// 检查当前页面是否是index.html
if (window.location.pathname.endsWith('index.html')) {
  document.getElementById('submitBtn').addEventListener('click', function(e) {
    e.preventDefault();
    window.location.href = 'another_file.html';
  });
}

方式2:通过页面标识判断

在index.html的<body>标签添加专属类名:

<body class="index-page">

然后在脚本中判断该类名是否存在:

if (document.body.classList.contains('index-page')) {
  document.getElementById('submitBtn').addEventListener('click', function(e) {
    e.preventDefault();
    window.location.href = 'another_file.html';
  });
}

方法三:拆分脚本文件

将仅属于index.html的逻辑单独拆分到一个脚本文件(比如index-script.js),只在index.html中引入这个脚本,second.html不引入它:
修改index.html的脚本引用:

<script src="index-script.js"></script>

这样从根源上避免了无关页面执行不需要的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:15:37