TypeScript:在事件中使用jquery $(this)

问题描述:

HTML:

<div>
<button data-id="3">Click Me</button>
</div>

在经典jQuery中,我会这样做:

In classic jQuery I would do:

$("div").on("click","button", test);

function test(){
   alert($(this).data("id"));
}

获取点击元素的data-id

在TypeScript(在类中)中,我使用:

In TypeScript (in a class) I use:

class foo { ...
 $("div").on("click", "button", (event) => this.test());

 public test(){
    alert($(this).data("id")); // "undefined"
    console.log($(this));
 }

....
}

在这里我没有得到单击的元素-$(this)是该类的实例.

Here I don't get the clicked element - $(this) is the instance of the class.

我做错了什么?

根据打字稿的规范"this"是指方法所属/被调用的类的实例.

According to Typescript's spec "this" is referring to the instance of class the method belongs to/is called on.

您可以使用传递给回调的事件对象的target属性:

You could use the target attribute of the event object passed to the callback:

class foo {
  public test(evt){
    alert($(evt.target).data("id")); // "undefined"
    console.log($(evt.target));
  }
}

还是event.currentTarget取决于您是否要实际单击元素或捕获事件的元素.

Or event.currentTarget depending on if you want to get the element actually clicked on or the element which captured the event.