在Javascript中克隆文件输入元素

Ant*_*ite 20 javascript jquery internet-explorer clone

我有一个文件输入元素,需要在用户浏览并选择要上传的文件后进行克隆.我开始使用obj.cloneNode(),一切正常,直到我尝试在IE中使用它.

我从那以后尝试使用jQuery的克隆方法如下:

var tmp = jQuery('#categoryImageFileInput_'+id).clone();
var clone = tmp[0];
Run Code Online (Sandbox Code Playgroud)

在FireFox中按预期工作,但同样不在IE中.

我被卡住了.有人有什么建议吗?

Mar*_*len 66

猜测你需要这个功能,所以你可以克隆输入元素并将其放入一个隐藏的形式,然后将其发送到一个隐藏的iframe ...

IE的element.clone()实现不会继承input type ="file"的值,所以你必须反过来:

// Clone the "real" input element
var real = $("#categoryImageFileInput_" + id);
var cloned = real.clone(true);

// Put the cloned element directly after the real element
// (the cloned element will take the real input element's place in your UI
// after you move the real element in the next step)
real.hide();
cloned.insertAfter(real);   

// Move the real element to the hidden form - you can then submit it
real.appendTo("#some-hidden-form");
Run Code Online (Sandbox Code Playgroud)

  • Chrome版本23.0.1271.101中的当前当前仍然失败。 (2认同)

小智 9

编辑文件表单字段存在安全风险,因此在大多数浏览器上被禁用,应该在firefox上禁用.依靠此功能并不是一个好主意.想象一下,如果有人能够使用javascript将隐藏文件上传字段更改为,比方说,

C:\用户\人\文件\财务

要么

C:\用户\人\应用程序数据\微软\为Outlook.pst

:)

  • 感谢您的快速回复,但要澄清(我不知道是否重要),我不是试图以任何方式编辑表单字段,我只需要克隆它.好吧,我确实需要稍后通过更改元素ID /名称来编辑它,但我不认为这是一个安全风险. (4认同)
  • 可笑的是,没有办法克隆文件输入元素并保留已选择的值。 (2认同)