【发布时间】:2019-08-09 17:18:08
【问题描述】:
当我写jQuery代码时,我使用$(this)来改变元素:
$('.classname').click(function(){
$(this).toggleClass('collapsed');
// ..
});
现在我有 javascript 类,看起来像这样:
class CabinetFormSize {
constructor() {
this.cabinetBTN = $(".cabinetBTN");
this.events();
}
events() {
this.cabinetBTN.click(this.toggleMenu.bind(this));
}
toggleMenu() {
console.log($(this));
this.cabinetBTN.toggleClass('d-none');
}
}
如果我在toggleMenu() 中写这个,我有类实例,但我需要元素。
console.log($(this))
如何在toggleMenu() 函数中使用$(this) 来获取元素?
如果我删除bind(this),console.log($(this)) 工作,但在这个字符串this.cabinetBTN.toggleClass('d-none') 我有Uncaught TypeError: Cannot read property 'toggleClass' of undefined。
【问题讨论】: