首页 > 解决方案 > 如何在 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

标签: jqueryoopthis

解决方案


不要将任何绑定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>


推荐阅读