Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

javascript - JavaScript:onchange函数导致错误/不起作用(JavaScript : onchange function causes error/ didn't work)

The Following code will add File upload and preview field.(以下代码将添加“ 文件上传和预览”字段。)

<b>This single img works but not in js</b> <br> <img id="img" alt="your image" width="100" height="100" /> <input type="file" onchange="document.getElementById('img').src = window.URL.createObjectURL(this.files[0])"> <br/> No of Img <input type="text" id="noi" name="noi" value="" onkeyup="addFields()"> <br /> <script> function addFields(){ // Number of inputs to create var number = document.getElementById("noi").value; // Container <div> where dynamic content will be placed var container = document.getElementById("container"); var array = ["CRICTICAL","HIGH","LOW","INFO"]; // Clear previous contents of the container while (container.hasChildNodes()) { container.removeChild(container.lastChild); } for (i=1;i<=number;i++){ var img = document.createElement("img"); img.width="100"; img.height="100"; img.id="img "+i; var upload = document.createElement("input"); upload.type="file"; //This part is Not Working_______________ upload.onchange="document.getElementById(img.id).src = window.URL.createObjectURL(this.files[0])"; //________________________________________ container.appendChild(img); container.appendChild(upload); container.appendChild(document.createElement("br")); } } </script> <div id="container"/> Problem :(问题:) Without the Container appendChild function the code works fine, you can see it in the first three lines of code.(没有Container appendChild函数,代码可以正常工作,您可以在代码的前三行中看到它。)   ask by vishal translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to run a function inside upload.onchange .(您必须在upload.onchange内部运行一个函数。)

Something like this:(像这样:) upload.onchange= function () { document.getElementById(img.id).src = window.URL.createObjectURL(this.files[0]) } Other way to do:(其他方式:) upload.addEventListener('change', function () { document.getElementById(img.id).src = window.URL.createObjectURL(this.files[0]) })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...