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

[英]TypeScript: Using jquery $(this) in event


HTML:

HTML:

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

In classic jQuery I would do:

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

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

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

To get the data-id of the clicked element

获取被点击元素的数据ID

In TypeScript (in a class) I use:

在TypeScript(在类中)我使用:

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

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

....
}

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

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

What did I do wrong?

我做错了什么?

3 个解决方案

#1


38  

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

根据Typescript的规范,“this”指的是方法所属/被调用的类的实例。

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

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

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

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

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

#2


17  

Using event.currentTarget worked for me when trying to get a data attribute of what was clicked.

在尝试获取所点击内容的数据属性时,使用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
}

#3


4  

By using arrow functions (event) => TypeScript is giving you a lexically bound this. (In compiled code a previously captured instance called _this)

通过使用箭头函数(event)=> TypeScript给你一个词法绑定。 (在已编译的代码中,以前捕获的实例称为_this)

If you switch to using vanilla function syntax you should be able to use $(this) as you would normally:

如果你切换到使用vanilla函数语法,你应该能够正常使用$(this):

$("div").on("click", "button", function(event) { this.test()});

Obviously you have an issue with the instance of the test method being called but I thought it worth sharing.

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

关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/04/03/1f1c5f0d49874fcf79ad18b7ce733e89.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com