How use JQuery $(this) in javascript Classes

≡放荡痞女 提交于 2021-02-16 15:25:52

问题


When I write jQuery code, I use $(this) to change element:

$('.classname').click(function(){
  $(this).toggleClass('collapsed');
  // ..
});

Now I have are javascript class, looks like this:

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

If i write this in toggleMenu() I have class instance, but I need the element.

console.log($(this))

How can I use $(this) in toggleMenu() function to take element? If i delete bind(this), console.log($(this)) work, but in this string this.cabinetBTN.toggleClass('d-none') i have Uncaught TypeError: Cannot read property 'toggleClass' of undefined.


回答1:


Don't bind any this to your callback. jQuery will call your callback with the correct this. Like

this.cabinetBTN.click(this.toggleMenu);

When you bind this to a function, you're basically creating a new function with a "hard-coded" this value.

My solution with a working snippet:

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>


来源:https://stackoverflow.com/questions/55236604/how-use-jquery-this-in-javascript-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!