繁体   English   中英

预览图像上传多个输入

[英]preview image upload more than one input

我有3个输入类型的文件,带有图像预览,问题是当我尝试为一个输入上传一个图像时,它将影响所有其他输入,这是我的代码:

<input type='file' onchange="readURL(this);" />    
<img class="blah" src="http://placehold.it/180" alt="your image" />
<input type='file' onchange="readURL(this);" />
<img class="blah" src="http://placehold.it/180" alt="your image" />
<input type='file' onchange="readURL(this);" />
<img class="blah" src="http://placehold.it/180" alt="your image" />

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('.blah')
        .attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
}

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> --> <!-- <script src="main.js"></script> --> <style> img{ width: 100px; height: 100px; } </style> </head> <body> <input type='file' data-result='file1' onchange="readURL(this);" /> <img name='file1' class="blah" src="Tulips.jpg" alt="your image" /> <input type='file' data-result='file2' onchange="readURL(this);" /> <img name='file2' class="blah" src="Tulips.jpg" alt="your image" /> <input type='file' data-result='file3' onchange="readURL(this);" /> <img name='file3' class="blah" src="Tulips.jpg" alt="your image" /> <script> function readURL(input) { debugger if (input.files && input.files[0]) { var reader = new FileReader(); var imageElementName= input.getAttribute('data-result'); reader.onload = function (e) { debugger //var imageElementName= input.getAttribute('data-result'); var el=document.getElementsByName(imageElementName); el[0].setAttribute('src',reader.result); // $('.blah') // .attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } </script> </body> </html> 

 function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $(input).next() .attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='file' onchange="readURL(this);" /> <img class="blah" src="http://placehold.it/180" alt="your image" /> <input type='file' onchange="readURL(this);" /> <img class="blah" src="http://placehold.it/180" alt="your image" /> <input type='file' onchange="readURL(this);" /> <img class="blah" src="http://placehold.it/180" alt="your image" /> 

您不应该直接附加.blah,它应该是当前输入的下一个元素

暂无
暂无

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

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