如何忽略querySelector抛出的错误 避免阻塞Logout函数执行
问题根因
你给所有class带nav-link的元素都绑定了分类加载的点击逻辑,但只有商品分类区域的导航项内部存在.items-title子节点,Logout、搜索、购物车、用户名展示这类导航链接里根本没有这个元素。querySelector找不到匹配目标时会返回null,这时候直接读取null.innerText会抛出TypeError,直接打断同点击事件链上的logout()函数执行。
修复方案
方案1:精准绑定事件(最推荐)
不要全量给所有.nav-link绑逻辑,只给实际包含.items-title的分类导航项绑定事件,从根源避免匹配到无关元素:
// 仅选中内部含.items-title的导航链接绑定事件 const categoryLinks = document.querySelectorAll('.nav-link:has(.items-title)'); for (let i = 0; i < categoryLinks.length; i++) { categoryLinks[i].onclick = (e) => { const current_child = e.currentTarget.querySelector('.items-title').innerText.trim(); let timerInterval; Swal.fire({ html: "Loading..", timer: 1000, icon: "info", timerProgressBar: true, allowEscapeKey: false, allowOutsideClick: false, showConfirmButton: false, showCancelButton: false, didOpen: () => { timerInterval = setInterval(() => { }, 100) }, willClose: () => { clearInterval(timerInterval); } }).then(() => { $.ajax({ url: "/Shop/Results", data: { result: current_child, }, type: "GET", dataType: "html", success: function (result) { $("#result").html(result); $(".false").html(result); } }) }) } }
额外提示:你原有代码里的
timerInterval没有做变量声明,直接赋值会泄漏成全局变量,建议在回调内部用let声明,避免后续出现计时器无法正常清除的问题。
方案2:空值判断兜底(兼容旧浏览器)
如果需要兼容不支持:has()选择器的低版本浏览器,可以在读取属性前先判断目标元素是否存在,不存在就直接终止分类加载逻辑,不会阻塞其他点击事件执行:
const allNavLinks = document.querySelectorAll('.nav-link'); for (var i = 0; i < allNavLinks.length; i++) { allNavLinks[i].onclick = (e) => { const titleEl = e.currentTarget.querySelector('.items-title'); // 没有找到对应子元素直接返回,不执行后续分类加载逻辑 if (!titleEl) return; const current_child = titleEl.innerText.trim(); let timerInterval; // 原有swal弹窗、ajax请求逻辑和之前完全一致 swal.fire({ html: "Loading..", timer: 1000, icon: "info", timerProgressBar: true, allowEscapeKey: false, allowOutsideClick: false, showConfirmButton: false, showCancelButton: false, didOpen: () => { timerInterval = setInterval(() => { }, 100) }, willClose: () => { clearInterval(timerInterval); } }).then(() => { $.ajax({ url: "/Shop/Results", data: { result: current_child, }, type: "GET", dataType: "html", success: function (result) { $("#result").html(result); $(".false").html(result); } }) }) } }
方案3:事件冒泡拦截(不推荐)
如果不想改动原有绑定逻辑,也可以在Logout、搜索这类不需要触发分类加载的导航项的点击回调里加事件阻止冒泡,避免触发通用的.nav-link点击逻辑,比如修改logout函数:
function logout() { // 阻止事件冒泡到.nav-link绑定的通用点击事件 event.stopPropagation(); // 你原有的登出提交逻辑 document.getElementById('logout').submit(); }
这个方案维护成本很高,后续新增导航项如果忘记加冒泡拦截,还会复现同类报错,只适合临时应急用。
内容的提问来源于stack exchange,提问作者Syfy
相关产品推荐
相关产品推荐

