處理同一頁面中藉助form+input[type="file"]上傳圖片出現的input無法清空問題,forminput
今天下午幫同事改了這樣一個bug:
在一個頁面中對多張圖進行上傳時,由於input的value無法情況的問題,導致每次選完圖片後,都跟第一張圖片一樣,無法出現如下效果:
百度了下思路:先將input取到,然後放到一個臨時form裡面清空,最後刪掉form.
代碼如下:
首先是產生圖片選擇和顯示部分的綁定代碼:
var img_tmp = '<tr><td><input type="text" name="code" value="" style="width: 90%; display: none;"><input type="text" name="title[]" style="width:90%;" /></td><td><input type="text" name="sort[]" style="width:90%;" /></td><td><input type="text" name="num[]" style="width:90%;"/></td>' + '<td><img alt="" src="" id="" name="img[]" style="max-width: 100px; max-height: 100px; display: block; float: left; border: 1px solid #E6E7EB;" /><div class="file_box">' + '<input type="button" class="btn" value="選擇圖片" />'+ '<input type="file" name="fileLOGO" class="file" id="" style="width: 80%;" onchange="UploadImages(this)" />' + '</div></td>' + '<td><a class="del" href="javascript:void(0)">刪除</a></td></tr>';
在onchange="UploadImages(this)" 這裡的方法中,我們傳入本次點擊的input,進行提交:
//多圖片上傳 function UploadImages(FileInput) { //var isno = fileChange($(FileInput)); //if (isno == undefined) { var options = { type: "POST", url: '../Handler/AshxUploadFile.ashx?type=Images', success: function (msg) { if (msg == "error") { clearImages($(FileInput)); showerrortip("上傳失敗"); } else { if (msg != "errortype") { clearImages($(FileInput)); $(FileInput).parent().prev("img").attr("src", strPic + msg); clearImages($(FileInput)); $(FileInput).attr("style", ""); } } }, error: function (msg) { clearImages($(FileInput)); $(FileInput).attr("style", ""); showerrortip("參數異常!"); } }; // 將options傳給ajaxForm $('form').ajaxSubmit(options); //} }
當時因為忽略了對input的清理,才導致了那個問題,為此,加入clearImages函數:
function clearImages(selector) { var fi; var sourceParent; if (selector) { fi = $(selector); sourceParent = fi.parent(); } else { return; } $("<form id='tempForm'></form>").appendTo(document.body); var tempForm = $("#tempForm"); tempForm.append(fi); tempForm.get(0).reset(); sourceParent.append(fi); tempForm.remove(); }
這樣,就利用臨時form清空了input.