TypeScript:在事件中使用jquery $(this) [英] TypeScript: Using jquery $(this) in event

查看:376
本文介绍了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.

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

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