2016-04-04 16 views
0

jqueryを使用してHTMLフォームからパスを選択した後にイメージを表示するサンプルコードがあります。コードはここにあります:htmlフォームからパスを選択した後に画像を表示

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <meta name="description" content=""> 
    <meta name="author" content=""> 
    <title>Image Test</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
    <script> 
    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]); 
     } 
    } 

    $("#imgInp").change(function(){ 
     readURL(this); 
    }); 
    </script> 
    </head> 

    <body> 
     <form id="form12" runat="server"> 
      <input type='file' id="imgInp" /> 
      <img id="blah" src="#" alt="your image" /> 
     </form> 

    </body> 
</html> 

しかし、画像を選択した後、パスが表示され、画像が表示されません。どこに問題がありますか?

+0

最後に 'body'の中に' script'タグを追加して、一度試してみてください。 –

答えて

2

最後にbodyタグが閉じる前にscriptタグを追加すると、scriptが実行される前にDOMが完全に読み込まれるようになります。

ここでは、あなたのコードが要素を探しているときに、まだDOMにロードされていないため、それを動作させることができませんでした。

<!DOCTYPE html> 
 
<html lang="en"> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="description" content=""> 
 
    <meta name="author" content=""> 
 
    <title>Image Test</title> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
</head> 
 

 
<body> 
 
    <form id="form12" runat="server"> 
 
    <input type='file' id="imgInp" /> 
 
    <img id="blah" src="#" alt="your image" /> 
 
    </form> 
 

 
<script> 
 
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]); 
 
    } 
 
} 
 

 
$("#imgInp").change(function() { 
 
    readURL(this); 
 
}); 
 
</script> 
 

 
</body> 
 

 
</html>

+0

これがOPの元のコードよりもうまくいく理由を説明してください。 – Scimonster

+0

投票の前に自分の答えを '追加/編集 'する時間を許してください。ありがとう。 –

+0

コードが動作しています。@ ThomasSebastian –

-2

あなたはpath.yourの画像srcが "#" 記号を持って指定していません。

+0

彼はsrc usign javascriptを追加しています –

関連する問題