JavaScript类与DOM操作报错:popUp未定义问题求助
问题分析与解决方案
核心错误原因
- 类方法调用错误:在
whenClickedgetter里调用popUp时未使用this,类的实例方法必须通过this访问,否则JS无法定位到该函数。 - 事件监听回调写法错误:
addEventListener需要传递函数引用,你直接写popUp(...)会立即执行函数,而非等待点击触发,需用箭头函数包裹来传递参数。 - Getter误用:Getter是属性而非方法,不能像调用函数那样加
(),比如dogWalking.whenClicked即可,无需dogWalking.whenClicked()。 - DOM选择器错误:
querySelector的选择符如果是类名要加.、id要加#,直接写"services_grid_container"会被当作标签名查找,必然找不到目标元素。 - animate参数格式错误:
Element.animate()仅接受两个参数——关键帧数组和配置对象,你拆分的三个参数需要合并。
修正后的完整代码
// 获取网格项 function mapContainers() { let values = ["1", "2", "3", "4", "5", "6"]; let gridItems = values.map((element) => { return document.querySelector(`.item${element}`); }); return gridItems; } // GridButton类 class GridButton { constructor(button, direction) { this.button = button; this.direction = direction; // 构造函数内直接绑定点击事件,逻辑更紧凑 this.bindClickEvent(); } // 绑定点击事件 bindClickEvent() { this.button.addEventListener("click", () => this.popUp(this.direction)); } // 弹窗动画方法 popUp(direction) { gridContainer.style.zIndex = "-1"; gridContainer.style.opacity = "0.2"; dogBone.style.display = "block"; dogBone.animate( [ { transform: "scale(0, 0)", transformOrigin: direction }, { transform: "scale(1, 1)" } ], { duration: 400, iterations: 1 } ); } } // 初始化函数 function init() { const gridItems = mapContainers(); // 修正了petWasteRemoval的网格项索引(原代码重复使用了gridItems[2]) new GridButton(gridItems[0], "top left"); new GridButton(gridItems[1], "top right"); new GridButton(gridItems[2], "left"); new GridButton(gridItems[3], "right"); new GridButton(gridItems[4], "bottom left"); new GridButton(gridItems[5], "bottom right"); } // DOM元素选择器修正(根据实际DOM结构调整.或#) const gridContainer = document.querySelector(".services_grid_container"); const serviceElaboration = document.querySelector(".service_elaboration"); const serviceElaborationText = document.querySelector(".service_elaboration_text"); const dogBone = document.querySelector(".dog-bone"); const dogBoneText = document.querySelector(".dog-bonetext"); // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', init);
额外优化说明
- 将事件绑定逻辑移至构造函数内,无需手动调用getter,代码结构更简洁。
- 修正了
petWasteRemoval对应的网格项索引,避免重复绑定同一元素。 - 移除了冗余的getter设计,直接在实例化时完成事件绑定,减少误用概率。
内容的提问来源于stack exchange,提问作者softhearthe
相关产品推荐
相关产品推荐

