如何实时判断用户是否选择了文件上传?

How to determine if user selected a file for file upload in real time?

假设,我有一个输入

<input id="uploadFile" type="file" />

在实时情况下,如果为此输入选择了文件,我需要输出警报。如果未选择文件并且用户只是关闭了文件管理器 window 我不需要输出警报。

我该怎么做?

您可以使用 change 事件来执行此操作。在该事件下,您可以检查文件输入的 value。如果为空,则没有选择文件。

$('#uploadFile').change(function() {
    if (this.value) {
        alert('you chose a file!');
    }
})

Working example

var x = document.createElement("INPUT");
x.setAttribute("type", "file");
x.setAttribute("id", "uploadFile");
x.onchange = function() {
    alert("File Selected");
}
document.body.appendChild(x);
/*
if(x.value == "") {
    alert("File is not Selected");
}
*/

这个例子可能对你有帮助。 W3Schools 最适合 JS。 http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files