簡體   English   中英

顯示來自表中文件輸入的圖像

[英]Display image from file input in table

如何顯示從文件輸入中選擇的圖像並將其顯示在表格中? 圖像未顯示在表格列中。 它顯示了alt屬性值。

 var tabData = [] var b; $(document).ready(function() { $('button').click(function() { var name = $('#uname').val(); var date = $('#date').val(); function readURL(input) { //here image chosse function if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { b = $('#blah').attr('src', e.target.result); //image loaded from file } reader.readAsDataURL(input.files[0]); } } $("#imgInp").change(function() { readURL(this); }); if (name == "" || date == "") { alert("please fill fileds") } else { var tblObj = { Name: name, Date: date, Image: b } //where b is image varibale which is choose from file input. tabData.push(tblObj); var data = ''; $('table').empty(); tabData.forEach(element => { data = '<tr><td>' + element.Name + '</td><td>' + element.Date + '</td><td>' + '<img src="' + element.Image + '" alt="image"/>' + '</td></tr>'; //I want to show image in table third column but it can not show image it display alt attribute value $('table').append(data); }); $('form').trigger("reset") } }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <form action="#"> Name:<input type="text" id="uname"> Date <input type="date" id="date"> Image: <input type='file' id="imgInp" /> <img id="blah" src="#" alt="your image" /> <button type="button">Submit</button> </form> </div> <div id="output"> <table> </table> </div>

顯示錯誤

未找到顯示

問題是因為您將處理圖像選擇的代碼放置在button單擊處理程序中 - 在您第一次嘗試提交表單之前不會調用它。

要解決此問題,請將#imgInp更改處理程序邏輯移至直接位於 document.ready 處理程序中:

 jQuery($ => { $("#imgInp").change(function() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = e => $('#blah').attr('src', e.target.result); reader.readAsDataURL(this.files[0]); } }); $('button').click(function() { // other logic not relevant to the issue... }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <form action="#"> Name:<input type="text" id="uname"> Date <input type="date" id="date"> Image: <input type='file' id="imgInp" /> <img id="blah" src="#" alt="your image" /> <button type="button">Submit</button> </form> </div> <div id="output"> <table></table> </div>

請注意, b將是一個 jQuery 對象,而不是您似乎期望的 base64 圖像源字符串。 如果您需要檢索該字符串,請直接設置b = e.target.result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM