【问题标题】:How use JQuery $(this) in javascript Classes如何在 javascript 类中使用 JQuery $(this)
【发布时间】: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

【问题讨论】:

    标签: jquery oop this


    【解决方案1】:

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

    this.cabinetBTN.click(this.toggleMenu);
    

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

    我的解决方案与工作的 sn-p:

    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>

    【讨论】:

    • 但是我如何在 toggleMenu() 中添加类似“this.cabinetNews.toggleClass("d-none")”的内容。没有绑定(这个),我有错误'未捕获的类型错误:无法读取未定义的属性'toggleClass'?
    • 什么是cabinetNews?我在您的代码中没有看到它。
    • 请看问题,我编辑的更准确。
    猜你喜欢
    • 1970-01-01
    • 2012-11-27
    • 2011-01-14
    • 2010-09-08
    • 1970-01-01
    • 2011-08-20
    • 2023-03-12
    • 2013-07-02
    • 2011-01-28
    相关资源
    最近更新 更多