简体   繁体   English

javascript 文件输入 onchange 不起作用 [仅限 ios safari]

[英]javascript file input onchange not working [ios safari only]

The code below works everywhere except on safari mobile.下面的代码适用于除 safari 手机以外的任何地方。 Apparently the onchange is never triggered.显然永远不会触发 onchange。

 // create a hidden file input element
 var input  = document.createElement("input");
 input.type = "file";
 
 // when the input content changes, do something
 input.onchange =
 function(event)
 {
  // upload files
 }

 // Trigger file browser
 input.click();

I have found similar examples however they all refer to scenarios where there is even a form of some other visible representation of the file input and they all involve form-clearing workarounds.我发现了类似的示例,但是它们都涉及甚至存在文件输入的某种其他可见表示形式的场景,并且它们都涉及表单清除解决方法。 That wouldn't work here.那在这里行不通。

This code is being called upon clicking a picture, in order to upload a new one as a replacement.单击图片时将调用此代码,以便上传新图片作为替换图片。

Any hints?有什么提示吗? Anything I'm doing wrong?我做错了什么吗?

I'll be damned: on iOS safari two extra conditions are necessary compared to other browsers:我会被诅咒:与其他浏览器相比,在 iOS Safari 上需要两个额外的条件:

1) The input must be actually appended to the DOM. 1) 输入必须实际附加到 DOM。

2) setting .onchange won't work: addEventListener must be used instead. 2) 设置 .onchange 不起作用:必须使用 addEventListener 代替。

should append input element to the real dom.应该将 append 输入元素到真实的 dom。

 // create a hidden file input element var input = document.createElement("input"); input.type = "file"; document.body.appendChild(input); // when the input content changes, do something input.onchange = function(event) { // upload files document.body.removeChild(input) } // Trigger file browser input.click();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM