这是一个更大项目的开始,但我在前端测试基础知识时遇到了错误。错误如下
Uncaught TypeError: Cannot read property 'addClass' of undefined
at HTMLDivElement.openOverlay (live-search.js?ver=1.0:20)
at HTMLDivElement.dispatch (jquery.js?ver=1.12.4-wp:3)
at HTMLDivElement.r.handle (jquery.js?ver=1.12.4-wp:3)
这是我到目前为止拥有的代码,目前我只是测试打开和关闭覆盖的触发器。
(function($) {
class Search {
constructor() {
this.openButton = $("#search-icon-btn");
this.closebutton = $(".search-overlay__close");
this.searchOverlay = $(".search-overlay");
this.events();
}
events() {
this.openButton.on("click", this.openOverlay);
this.closebutton.on("click", this.closeOverlay);
}
openOverlay() {
this.searchOverlay.addClass("search-overlay--active");
}
closeOverlay() {
this.searchOverlay.removeClass("search-overlay--active");
}
}
var liveSearch = new Search();
})(jQuery);
任何帮助都将不胜感激!
发布于 2019-08-28 08:09:22
当openOverlay作为事件处理程序被调用时,"this“会被覆盖。在这种情况下,我相信它会引用openButton (发送者),而不是Search实例。因此,this.searchOverlay将是未定义的。
有几种方法可以解决这个问题。您可以使用bind方法显式绑定“this”。
events() {
this.openButton.on("click", this.openOverlay.bind(this));
this.closebutton.on("click", this.closeOverlay.bind(this);
}
或者,您可以设置openOverlay和closeOverlay来接收对搜索实例的引用。
events() {
this.openButton.on("click", () => this.openOverlay(this));
this.closebutton.on("click", () => this.closeOverlay(this));
}
openOverlay(self) {
self.searchOverlay.addClass("search-overlay--active");
}
closeOverlay(self) {
self.searchOverlay.removeClass("search-overlay--active");
}
https://stackoverflow.com/questions/57683448
复制相似问题