首页 > 解决方案 > jQuery - 选择图像后不触发 .change()

问题描述

我正在编写一段代码来加载图像并在 <img>标签中显示图像预览,它在 chrome 和 Firefox 上完美运行,但在 Microsoft Edge 上却不行。我进行了非常深入的搜索,但找不到任何相关的解决方案,也许有人遇到了我在网上找不到的类似问题。无论如何,当我执行 console.log 尝试调试问题时,发现 .change() 不起作用。(注意,它会加载一个大约 20 KB 的小 jpeg 图像,但如果它大于 25 KB 将无法工作,并且需要至少尝试 2 次才能加载小图像)这里是文件

$(document).ready(function(e) {     
$('.img_upload img').bind("click" , function () {   
     var img=$(this);
     var input=img.next(".send_photo_input");
 input.trigger("click");
 input.change(function(){
         console.log("trigger the input");                   
         var preview= $(".send_photo_img");

       var file=document.querySelector('input[type=file]').files[0];
        var reader=new FileReader();            
       reader.addEventListener("load",function(){
          console.log("this is before preview");

         preview.attr("src",reader.result);

           console.log("after preview");                

       },false);  //end of the listening           
       if(file)
       {
           console.log("inside if");
           reader.readAsDataURL(file);
       }
       else
       {
           console.log("inside else");
       }        
    });

 });

});

上面的文件是ex1.js

   <!DOCTYPE html>
    <html>
    <head>
   <meta charset="UTF-8">
   <link rel="stylesheet" href="ex.css">
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Untitled Document</title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="ex1.js"></script>
   </head>
   <body>
        <div class="img_upload">
           <img class="send_photo_img" id="send_photo1_img" src="left.png"/>
           <input id="send_photo1" name="send_photo1" class="send_photo_input" 
    type="file"/>
       </div>
  </body>
  </html>      

ex.css 只是带有 display:none 来隐藏输入元素

它不在 Microsoft Edge 上。我一直在调试这个问题,需要一些帮助来解决这个问题,在此先感谢。

标签: javascriptjqueryhtmlmicrosoft-edge

解决方案


尝试使用on

input.on('change',function(){
//rest of the code
})

推荐阅读