2

我正在使用 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
4

1 回答 1

3

问题是,除了.get()返回一个数组(.get(0)给你第一个元素)你使用.attr()而不是.prop().

如果需要elem.files,访问它的 jQuery 方法是$(elem).prop('files').

使用时.attr(),它对应于.getAttribute()通常不是您想要的属性的调用,例如filesor checked。jQuery 有时会自动切换到属性,例如 for checked,但当然它不能涵盖每一个属性。

因此,您最终要使用的是$('#inputFile').prop('files')or $("#inputFile").get(0).files。但是,如果您的选择器不匹配任何内容,后者将引发错误。

于 2012-04-24T10:45:05.030 回答