清除<输入类型='文件'/>使用 jQuery [英] Clearing <input type='file' /> using jQuery

查看:45
本文介绍了清除<输入类型='文件'/>使用 jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 jQuery 清除 <input type='file'/> 控件值?我尝试了以下方法:

Is it possible to clear an <input type='file' /> control value with jQuery? I've tried the following:

$('#control').attr({ value: '' }); 

但它不起作用.

推荐答案

简单:你在元素周围包裹一个

,在表单上调用 reset,然后使用 .unwrap().与此线程中的 .clone() 解决方案不同,您最终会得到相同的元素(包括在其上设置的自定义属性).

Easy: you wrap a <form> around the element, call reset on the form, then remove the form using .unwrap(). Unlike the .clone() solutions otherwise in this thread, you end up with the same element at the end (including custom properties that were set on it).

在 Opera、Firefox、Safari、Chrome 和 IE6+ 中测试和工作.也适用于其他类型的表单元素,type="hidden" 除外.

Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden".

window.reset = function(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <input id="file" type="file">
  <br>
  <input id="text" type="text" value="Original">
</form>

<button onclick="reset($('#file'))">Reset file</button>
<button onclick="reset($('#text'))">Reset text</button>

JSFiddle

正如 Timo 在下面指出的,如果您有按钮来触发 内的字段重置,则必须调用 .preventDefault() on防止 <button> 触发提交的事件.

As Timo notes below, if you have the buttons to trigger the reset of the field inside of the <form>, you must call .preventDefault() on the event to prevent the <button> from triggering a submit.

由于未修复的错误,无法在 IE 11 中运行.文本(文件名)在输入中被清除,但它的 File 列表仍然被填充.

Does not work in IE 11 due to an unfixed bug. The text (file name) is cleared on the input, but its File list remains populated.

这篇关于清除&lt;输入类型='文件'/&gt;使用 jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆