如何在 javascript 类中使用 JQuery $(this) [英] How use JQuery $(this) in javascript Classes

查看:41
本文介绍了如何在 javascript 类中使用 JQuery $(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编写jQuery代码时,我使用$(this)来改变元素:

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

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

现在我有 javascript 类,看起来像这样:

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

如果我在 toggleMenu() 中写这个,我有类实例,但我需要元素.

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

console.log($(this))

如何在 toggleMenu() 函数中使用 $(this) 来获取元素?如果我删除 bind(this)console.log($(this)) 工作,但在这个字符串 this.cabinetBTN.toggleClass('d-none') 我有 Uncaught TypeError: Cannot read property 'toggleClass' of undefined.

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.

推荐答案

不要将任何 this 绑定到您的回调.jQuery 将使用正确的 this 调用您的回调.喜欢

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

this.cabinetBTN.click(this.toggleMenu);

当您将 this 绑定到一个函数时,您基本上是在创建一个具有硬编码"this 值的新函数.

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>

这篇关于如何在 javascript 类中使用 JQuery $(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆