我正在使用 jquery 对 html 5 文件上传进行一些测试,但遇到了一些奇怪的事情(至少对我而言)。我试图获取已在文件控件中选择的文件列表:
<html><head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
</head>
<body>
<input type="file" multiple="multiple" id="inputFile" name="inputFile">
<button onclick="buttonClicked()" type="button">upload</button>
<script type="text/javascript">//<![CDATA[
function buttonClicked() {
console.log($("#inputFile").val()); // depending on the browser, gives either the file name, either the full path, but only for the first file
console.log($("#inputFile").files); // gives undefined
console.log($("#inputFile").attr("files")); // gives undefined
console.log($("#inputFile").get()); // according to the jquery documentation, give the dom element...
console.log($("#inputFile").get().files); // ...but strangely, files is undefined
console.log($("#inputFile")[0].files); // on the other hand, this gives me the list of files
}
//]]>;
</script>
</body></html>
所以首先我期待 $("#inputFile").val() 会给我至少,太糟糕了,事实并非如此。所以我尝试了 input.files 的变体,并没有真正期望它能够工作,因为它似乎不适合 jquery 对象(但是嘿,你永远不知道)。所以我尝试从 jquery 获取底层 dom 元素来访问 files 项。这就是它变得奇怪的地方,因为它也是未定义的。另一方面,$("#inputFile")[0].files 给出了预期的结果。
[编辑] 然后,像往常一样,在输入这个问题时,我自己找到了解决方案。无论如何我都会把它留在这里,所以任何为此奋斗的人也有机会解决它。它基本上在 RRTFM 上运行,就像真的 RTFM 一样:
此调用返回所有匹配的 DOM 节点,包含在标准数组中
这意味着,即使只有一个元素。所以调用:
console.log($("#inputFile").get());
返回一个包含一个元素的数组,当然数组没有files
属性。它应该是:
console.log($("#inputFile").get(0));
console.log($("#inputFile").get()[0]); // or this one, but that's a bit silly