我在Angular组件的ngOnInit中编写了一个JQuery代码片段。这样做的目的是当在模板html中选择文件时触发一种方法。

以下JQuery已用ngOnInit编写。请注意,它使用箭头功能。

$(document.body).on("change.bs.fileinput", ".fileinput-exists", () => {
    alert("fired");
    // do file upload stuff
    // for that, access the current input field and get the uploaded file
});


为了处理文件,我需要访问它。为此,我需要在箭头功能中可以访问当前输入字段。

我该如何通过?我尝试使用$(this)作为箭头函数参数。它给了我一个编译错误。

要么

我应该通过活动吗? (event : EventTarget)作为箭头功能参数。

最佳答案

“问题”带有箭头功能。其实这不是问题,但这是一个功能。使用箭头函数,您将不会更改this的上下文,而不会更改普通函数的行为。
因此,如果要使用箭头功能,请通过选择器再次选择元素,因为您无法使用其中的$(this)
否则(更好),您可以按照概述通过jQuery访问event.currentTarget
但是,如果您的组件与相同的输入字段相关联,则应该能够通过$element引用仅使用angular来访问它(这要好得多)

下面是使用event.currentTarget的示例:

$(document.body).on("change.bs.fileinput", ".fileinput-exists", (event) => {
    alert($(event.currentTarget));
    // do file upload stuff
    // for that, access the current input field and get the uploaded file
});

关于javascript - 将当前的JQuery对象传递给TypeScript箭头函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44118782/

10-12 00:26
查看更多