TypeScript:在事件中使用 jquery $(this)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22843255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript: Using jquery $(this) in event
提问by mdunisch
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-idof the clicked element
获取data-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?
我做错了什么?
回答by Laszlo Korte
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:
您可以使用传递给回调的事件对象的目标属性:
class foo {
public test(evt){
alert($(evt.target).data("id")); // "undefined"
console.log($(evt.target));
}
}
Or event.currentTargetdepending on if you want to get the element actually clicked on or the element which captured the event.
或者event.currentTarget取决于您是要实际单击元素还是捕获事件的元素。
回答by Billy
Using event.currentTargetworked 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
}
回答by John Reilly
By using arrow functions (event) => TypeScriptis giving you a lexically bound this. (In compiled code a previously captured instance called _this)
通过使用箭头函数(event) => TypeScript给你一个词法绑定 this。(在已编译的代码中,之前捕获的实例称为_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.
显然,您在调用测试方法的实例时遇到了问题,但我认为值得分享。

