javascript file input onchange not working [ios safari only]

主宰稳场 提交于 2019-12-06 01:48:28

问题


The code below works everywhere except on safri mobile. Apparently the onchange is never triggered.

 // 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?


回答1:


I'll be damned: on iOS safari two extra conditions are necessary compared to other browsers:

1) The input must be actually appended to the DOM.

2) setting .onchange won't work: addEventListener must be used instead.



来源:https://stackoverflow.com/questions/47664777/javascript-file-input-onchange-not-working-ios-safari-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!