下記の記事を基に画像アップロードの際に即時プレビューが反映される機能を実装途中です。
https://whatsupguys.net/programming-school-dive-into-code-learning-88/
問題点
filefieldをクリックし画像の決定、もしくはリセットを押した後に再度ポップアップが実行されます。
下記にgif動画にてご報告させていただきます。
https://gyazo.com/46fa3c50955db97adec4267d6da4950c
実現したいこと
実行を1回のみにしたいのですが、ご教授お願い申し上げます。
###確認したこと
別のjsで重複した処理が行われていないか確認しました。
重複して処理している部分はありませんでした。
(同じID名に対して当てていないかの確認)
js
1$(function(){ 2 $fileField = $('#file') 3 $($fileField).on('change', $fileField, function(e) { 4 file = e.target.files[0] 5 reader = new FileReader(), 6 $preview = $("#img_field"); 7 8 reader.onload = (function(file) { 9 return function(e) { 10 $preview.empty(); 11 $preview.append($('<img>').attr({ 12 src: e.target.result, 13 width: "100%", 14 class: "preview", 15 title: file.name 16 })); 17 }; 18 })(file); 19 reader.readAsDataURL(file); 20 }); 21});
gem
1gem 'turbolinks', '~> 5'
application.html.haml
application.html.haml
1!!! 2%html{:lang => "ja"} 3 %head 4 %meta{:content => "_8qthwiKuurqXKMdAxNyavTr0wVLoNead8ZQF9v_x5E", :name => "google-site-verification"}/ 5 %meta{:charset => "utf-8"} 6 %meta{:content => "width=device-width, initial-scale=1, shrink-to-fit=no", :name => "viewport"}/ 7 = csrf_meta_tags 8 9 %title hoguhogu 10 11 -# googleフォント 12 %link{:href => "https://fonts.googleapis.com/icon?family=Material+Icons", :rel => "stylesheet"}/ 13 %link{:href => "https://fonts.googleapis.com/css?family=Roboto", :rel => "stylesheet"}/ 14 -# ブートストラップ 15 %link{:crossorigin => "anonymous", :href => "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css", :integrity => "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T", :rel => "stylesheet"}/ 16 -# ーーーーーーーーー 17 = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' 18 19 -# ブートストラップ 20 %script{:crossorigin => "anonymous", :integrity => "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo", :src => "https://code.jquery.com/jquery-3.3.1.slim.min.js"} 21 %script{:crossorigin => "anonymous", :integrity => "sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1", :src => "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"} 22 %script{:crossorigin => "anonymous", :integrity => "sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM", :src => "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"} 23 -# ーーーーーーーーー 24 25 = javascript_include_tag 'application', 'data-turbolinks-track': 'reload' 26 %body 27 = yield
回答1件
あなたの回答
tips
プレビュー