本文介绍了通过JavaScript清除HTML文件上传字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户选择另一个选项时重置文件上传字段。

I want to reset a file upload field when the user selects another option.

这是可以通过JavaScript吗?我怀疑文件上传元素的处理方式不同,因为它与用户的文件系统交互,也可能是不可变的。

Is this possible via JavaScript? I'm suspecting that the file upload element is treated differently because it interacts with the user's file system, and maybe it's immutable.

基本上,我想要的是类似伪代码):

Basically, what I want is something like (pseudo-code):

// Choose selecting existing file
$('#select-file').bind('focus', function() {
  // Clear any files currently selected in #upload-file
  $('#upload-file').val('');
}) ;

// Choose uploading new one - this works ok
$('#upload-file').bind('focus', function() {
  // Clear any files currently selected in #select-file
  $('#select-file').val('');
}) ;


推荐答案

您无法在大多数浏览器中设置输入值,但你可以做的是创建一个新元素,从旧元素复制属性,并交换两个。

You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.

给定一个表单:

<form>
    <input id="fileInput" name="fileInput" type="file" />
</form>

直线DOM方式:

The straight DOM way:

function clearFileInput(id)
{
    var oldInput = document.getElementById(id);

    var newInput = document.createElement("input");

    newInput.type = "file";
    newInput.id = oldInput.id;
    newInput.name = oldInput.name;
    newInput.className = oldInput.className;
    newInput.style.cssText = oldInput.style.cssText;
    // TODO: copy any other relevant attributes

    oldInput.parentNode.replaceChild(newInput, oldInput);
}

clearFileInput("fileInput");

简单的DOM方式。这可能不适用于不喜欢文件输入的旧浏览器:

Simple DOM way. This may not work in older browsers that don't like file inputs:

oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);

jQuery方式:

The jQuery way:

$("#fileInput").replaceWith($("#fileInput").val('').clone(true));

// .val('') required for FF compatibility as per @nmit026

通过jQuery重置整个表单:

Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947

这篇关于通过JavaScript清除HTML文件上传字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 01:24