:file

选择所有文件上传元素,即 type 为 file 的元素。

:file 等价于 [type="file"].如其它伪类选择器(以 ":" 开头的选择器)一样,建议使用此类选择器时,跟在一个标签名或者其它选择器后面,否则,默认使用了全局通配符选择器 "*"。换句话说,$(':file') 等价于 $('*:file'),所以应该使用 $('input:file') 来提升匹配效率。

补充说明:

  • 由于 :file 是 jQuery 扩展出来的,它并不是 CSS 规范中的一部分。当使用 :file 时,并不会比使用原生的 DOM 方法 querySelectorAll() 性能好。为了在主流浏览器中得到更好的性能,请使用 [type="file"] 方法来代替。

示例:

查找所有文件上传元素。

<!DOCTYPE html>
<html>
<head>
<style>
  textarea { height:45px; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option<option/></select>

    <textarea></textarea>
    <button>Button</button>
  </form>
  <div>
  </div>

<script>



    var input = $("input:file").css({background:"yellow", border:"3px red solid"});
    $("div").text("For this type jQuery found " + input.length + ".")
            .css("color", "red");
    $("form").submit(function () { return false; }); // so it won't submit



</script>
</body>
</html>

演示: