JS Toast通知函数出现‘element.classList is undefined’错误的原因
Toast通知自动隐藏时抛出TypeError的原因及修复
问题代码
HTML
<div id="notifications"></div>
JavaScript
const notify = (type, text, autohide = true) => { const box = `<div class="notification ${type}">${text}<span onclick="notifyHide(parentNode)"></span></div>`; notifications.insertAdjacentHTML("afterbegin", box); if (autohide) setTimeout(() => { notifyHide(box); }, 5000); }; const notifyHide = el => { el.classList.add("hide"); setTimeout(() => { el.remove(); }, 500); };
错误原因
当autohide为true时,你传入notifyHide的box是一个HTML字符串,而非实际的DOM元素。insertAdjacentHTML方法只是将这个字符串解析为DOM节点插入到页面中,但box变量本身依然是字符串类型——字符串没有classList属性,自然会抛出undefined的错误。
而点击关闭按钮时,notifyHide(parentNode)中的parentNode是真实的DOM元素(即生成的.notification容器),所以能正常调用classList相关方法。
修复方案
方案1:插入后获取真实DOM元素
利用afterbegin插入位置的特性,直接取父容器的第一个子元素作为目标DOM:
const notify = (type, text, autohide = true) => { const box = `<div class="notification ${type}">${text}<span onclick="notifyHide(parentNode)"></span></div>`; notifications.insertAdjacentHTML("afterbegin", box); // 获取刚插入的通知元素 const notificationEl = notifications.firstElementChild; if (autohide) setTimeout(() => { notifyHide(notificationEl); }, 5000); };
方案2:直接创建DOM元素(更推荐)
放弃字符串模板,用原生DOM API创建元素,全程操作真实节点:
const notify = (type, text, autohide = true) => { // 创建通知容器 const notificationEl = document.createElement('div'); notificationEl.className = `notification ${type}`; notificationEl.textContent = text; // 创建关闭按钮 const closeBtn = document.createElement('span'); closeBtn.onclick = () => notifyHide(notificationEl); notificationEl.appendChild(closeBtn); // 插入到通知容器最前面 notifications.prepend(notificationEl); // 自动隐藏逻辑 if (autohide) setTimeout(() => { notifyHide(notificationEl); }, 5000); };
内容的提问来源于stack exchange,提问作者AbsoluteBeginner
相关产品推荐
相关产品推荐

