javascript - 在 jQuery 的拖动事件中使用在类中定义的方法

标签 javascript jquery function class reference

您好,我的引用资料有问题。 例如:

    class Inset{

        constructor(){
            this.x = 1;
            this.y = 2;
            this.divBox = $('<div></div>);
            this.divBox.draggable({drag: function(event, ui){
                //Here i want to call the add funciton with my x and y but i dont get it, how i can reference to the add function.
            }})
        }

        add(x, y){
            return x+y;
        }
    } 

如何从 Inset 类中调用函数 add(x,y)?

最佳答案

试试这个:

JS

class Inset {
  constructor(){
    this.x = 1;
    this.y = 2;
    this.divBox = $('.draggable');
    this.divBox.draggable({ 
      drag: (event, ui) => {
        this.add(10,20);
      }
    });
  }

  add(x, y){
    console.log(x, y);
    return x + y;
  }
} 

new Inset();

CSS

.draggable {
  border: 2px solid #000;
  height: 20px;
  width: 20px;
}

HTML

<div class="draggable"></div>

DEMO

关于javascript - 在 jQuery 的拖动事件中使用在类中定义的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51573625/

相关文章:

jquery - 检查密码和登录有效性

javascript - jquery根据查询字符串删除标签

c - scanf 在 C 中捕获带有\0 和一串零的 char 类型字符串

c++ - c++中的函数返回如何工作

javascript - 如何使用 React 从 Promise 函数将带有键的数组输出到我的 html 文件

javascript - 如何在 Div 中按下按钮

javascript - 自动加载新页面,仅访问正文中的元素

javascript - 单击事件不适用于动态创建的按钮

javascript - 如何使用 WebdriverIO (wdio) 获取元素出现的次数?

javascript - 跨页面拉伸(stretch) div 不起作用