复用首页按钮跳转函数至其他页面报错,需实现同页面重定向
问题解决:头部按钮复用的报错与跳转逻辑优化
报错根源
你遇到的报错是因为非首页的页面中不存在.titleAndMenuIcon > img、.mobilePopUp__login这些DOM元素,document.querySelector()会返回null,直接调用addEventListener()自然会抛出"Cannot read properties of null"的错误。
解决方案
1. 先检查DOM元素是否存在再绑定事件
修改两个函数,在绑定事件前先判断元素是否存在,避免null报错:
function getHeaderButtons() { const showHidePopUp = document.querySelector('.titleAndMenuIcon > img') const windowPopUP = document.querySelector('.mobilePopUp') // 先检查元素是否存在,再绑定事件 if (showHidePopUp && windowPopUP) { showHidePopUp.addEventListener('click', () => { windowPopUP.classList.toggle('moveUpAndDown') console.log('ok') }) } }
function getLoginAndSubscribeButtons() { const login = document.querySelector('.mobilePopUp__login') const subscribe = document.querySelector('.mobilePopUp__subscribe') const currentPath = window.location.pathname // 处理登录按钮 if (login) { login.addEventListener('click', () => { window.location.href = "./src/pages/loginPage.html" }) } // 处理订阅按钮,支持当前在订阅页面时的跳转需求 if (subscribe) { subscribe.addEventListener('click', () => { const targetUrl = './src/pages/subscribePage.html' // 如果当前已经在订阅页面,刷新页面;否则跳转 if (currentPath.includes('/subscribePage.html')) { window.location.reload() } else { window.location.href = targetUrl } }) } }
2. 补充说明
- 元素存在性检查是通用的复用基础逻辑,确保函数在任何页面运行都不会因为找不到元素报错。
- 订阅按钮的逻辑里,通过
window.location.pathname判断当前页面路径,如果已经在订阅页面,调用reload()刷新页面;如果不在,则正常跳转。如果你希望即使在订阅页面也强制跳转(浏览器会自动处理为刷新),也可以直接保留原跳转代码,去掉路径判断,效果类似。
内容的提问来源于stack exchange,提问作者newuser12333
相关产品推荐
相关产品推荐

