addClass jQuery throw



这是一个更大项目的开始,但是当我在前端测试基础知识时遇到了错误。错误如下

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);

任何帮助将不胜感激!

当 openOverlay 作为事件处理程序调用时,"this"会被覆盖。在这种情况下,我相信它会引用 openButton(发件人(而不是搜索实例。因此,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/a/20279485/11981207

最新更新