jquery - 如何在 javascript 类中使用 JQuery $(this)
问题描述
当我编写 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))
如何$(this)
在toggleMenu()
函数中使用元素?如果我删除bind(this)
,console.log($(this))
工作,但在这个字符串中this.cabinetBTN.toggleClass('d-none')
我有Uncaught TypeError: Cannot read property 'toggleClass' of undefined
。
解决方案
不要将任何绑定this
到您的回调。jQuery 将使用正确的this
. 喜欢
this.cabinetBTN.click(this.toggleMenu);
当您绑定this
到一个函数时,您基本上是在创建一个具有“硬编码”this
值的新函数。
我的解决方案有一个工作片段:
class CabinetFormSize {
constructor() {
this.cabinetBTN = $(".cabinetBTN");
this.events();
}
events() {
this.cabinetBTN.click(this.toggleMenu);
}
toggleMenu() {
console.log($(this).text())
}
}
new CabinetFormSize();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cabinetBTN">Click me</div>
推荐阅读
- javascript - 如何在three.js中加载gLTF
- cmake - 如何使用 CMake 从项目外部导入 proto 文件?
- identityserver3 - 在 IdentityServer3 的受众中包括资源范围?
- javascript - 如何使用 firebase-admin 模块从带有 Node.js 的 Firebase 数据库返回有序数据?
- r - 合并数据集而不丢失数据
- ruby-on-rails - 遍历表单发布数据上的多个字段
- android - [Android]EditText焦点释放时防止隐藏键盘
- python - 如何将一个 Jupyter 笔记本导入另一个
- c# - 在 Automapper 中映射集合
- python - 如何将调试控制台设置为 Visual Studio Code 中的默认选项卡?