【发布时间】:2021-09-23 13:10:43
【问题描述】:
我想写一个小的 JavaScript 库。
这很简单。它是一个上传文件的小包装器。
无论如何:我在事件中访问实例时遇到问题。
我是这样尝试的:
class FileUpload
{
constructor(element)
{
this.element = element;
this.dropDiv = document.createElement("div");
this.dropDiv.style = "border: 2px solid #007bff; background-color: lightblue; width: 100%;border-radius: 25px;";
this.dropDiv.className = "text-center";
this.dropDiv.innerHTML = "Upload<br>File<br>Here";
this.dropDiv.addEventListener("dragover", function(event)
{
event.preventDefault();
});
this.dropDiv.addEventListener("drop", this.dropHandler);
this.element.appendChild(this.dropDiv);
}
dropHandler(event)
{
event.preventDefault();
this.uploadFile("Test");
}
uploadFile(file)
{
console.log("Logic to Upload the file or whatever...");
console.log(file);
}
}
它给了我错误: this.uploadFile 不是函数
如果我这样尝试:
.....
this.dropDiv.addEventListener("drop", this.dropHandler('Test'));
this.element.appendChild(this.dropDiv);
}
dropHandler(testVar)
{
console.log(testVar);
console.log(this);
this.uploadFile("Test");
}
uploadFile(file)
{
console.log("Logic to Upload the file or whatever...");
console.log(file);
}
它有效。但我的问题是:我需要事件处理程序。
获取发送者没问题(this.element / this.dropDiv, ...)
但是我如何通过参数和 FileUpload 实例获取事件?
谢谢!
【问题讨论】:
标签: javascript class oop dom-events instance