gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:29:30 26 4
gpt4 key购买 nike

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) 是类的实例。

我做错了什么?

最佳答案

根据 Typescript's spec “this”指的是该方法所属/被调用的类的实例。

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

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

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

关于jquery - TypeScript:在事件中使用 jquery $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22843255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com