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

40

HTML:

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

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

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

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

获取被点击元素的 data-id

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

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

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

....
}

我在这里没有得到被点击的元素 - $(this) 是类的实例。

我做错了什么?


1
你没有做错任何事情 - TypeScript 过于热心了。在类方法内部,this 被视为始终指向相应的对象。因此,你有两个解决方案 - 要么使用 event.target 属性捕获点击的元素,要么将处理程序函数定义在该类之外。 - raina77ow
据我所见,大多数答案都不完整或错误。请访问我的答案:http://stackoverflow.com/questions/38159416/using-the-this-in-event-handler-with-typescript/38159643?noredirect=1#comment63747929_38159643 - Mohammad Hossein Amri
3个回答

47
根据Typescript规范,“this”指的是方法所属的类的实例/被调用的实例。
您可以使用传递给回调函数的事件对象的target属性:
class foo {
  public test(evt){
    alert($(evt.target).data("id")); // "undefined"
    console.log($(evt.target));
  }
}

或者,根据您想要获取实际单击的元素还是捕获事件的元素,可以使用 event.currentTarget

4
我使用 **$("div").on("click", "button", (event) => this.test(event));**,并在函数中: public test(element:JQueryEventObject){ $(element.target) }.... 它有效了 - 谢谢! - mdunisch
1
@user3351722:谢谢。这解决了同时访问事件目标和类的实际问题。 - realbart

23

在我尝试获取被点击元素的数据属性时,使用event.currentTarget对我很有用。

$('.elementID').click(e => this.clickedElement(e));


clickedElement(e: JQueryEventObject) {
    var iWasClickedData = $(this).data('key'); // will not work
    var iwasClickedDataFixed = $(e.currentTarget).data('key'); // will work
}

我也试过了,谢谢你! - Manas Bajaj

4
通过使用箭头函数(event) => TypeScript,TypeScript会给你一个词法绑定的this。在编译后的代码中,之前捕获的实例被称为_this
如果您切换到使用普通函数语法,您应该能够像往常一样使用$(this)
$("div").on("click", "button", function(event) { this.test()});

显然,你的问题出在测试方法实例的调用上,但我认为值得分享。

我不得不使用这个答案而不是建议的答案,因为我尝试使用自己的扩展方法来扩展jQuery.fn时遇到了相同的问题,它不像事件那样提供“this”的替代引用。 - NightWatchman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接