我有一个按钮将其表现为定位标记或链接。单击按钮时,在下面的代码中添加了它。
download() {
let link = document.createElement('a');
document.body.appendChild(link);
//link.href = this.downloadFile; // can i call a function here which has API invoking?
link.onclick = this.downloadFile;
link.click();
}
downloadFile() {
this.Service.download(
id
).subscribe((data: any) => {
},
(error: any) => {
});
}
如何在创建锚标记后调用此功能?
而不是使用link.onclick,而是在链接上使用addEventListener方法来注册您的下载方法:
function download() {
var link = document.createElement('a');
document.body.appendChild(link);
link.addEventListener('click', this.downloadFile);
link.click();
}
function downloadFile() {
console.log("Here we go");
}
但是要小心,因为如果您的方法downloadFile是一个类方法,那么downloadFile函数中的“ this”将是未定义的或等于窗口全局对象,并且您将必须使用link.addEventListener('click ',this.downloadFile.bind(this));