以下代码将添加文件上传和预览字段。
<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"/>
问题:
没有Container appendChild函数,代码可以正常工作,您可以在代码的前三行中看到它。
答案 0 :(得分:0)
您必须在upload.onchange
中运行一个函数。像这样:
upload.onchange= function () {
document.getElementById(img.id).src = window.URL.createObjectURL(this.files[0])
}
其他方式:
upload.addEventListener('change', function () {
document.getElementById(img.id).src =
window.URL.createObjectURL(this.files[0])
})
答案 1 :(得分:0)
已解决的问题
工作正常。
所有图像字段都可以执行
<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";
upload.id="upload "+i;
//Working_______________
upload.onchange=upload.onchange= function () {
var img_id=this.getAttribute('id');
var imgId = img_id.charAt(7) ;
document.getElementById("img "+imgId).src = window.URL.createObjectURL(this.files[0])
}
//________________________________________
container.appendChild(img);
container.appendChild(upload);
container.appendChild(document.createElement("br"));
}
}
</script>
<div id="container"/>