解決Layui tpl模板渲染檔案上傳不起作用
阿新 • • 發佈:2019-08-11
Html
<div class="weui_cells " id="ordersView"> <script type="text/html" id="ordersTpl"> {{# if (item.zhifufssjz === '2') { }} <div class="weui_cell"> <div class="weui_cell_bd weui_cell_primary"> <a href="javascript:void(0);" class="file">上傳購買憑證 <input id="file" class="weui_input upload" type="file" accept="image/*" name="file"/> </a> </div> <div class="weui_cell_ft "> <img id="Img" style="height: 50px;"> </div> </div> {{# } }} </script> </div> <!--檔案上傳按鈕--> <button type="button" style="display: none;" class="layui-btn" id="fileUploadAction">開始上傳</button>
關鍵程式碼:
<input id="file" class="weui_input upload" type="file" accept="image/*" name="file"/>
JS
/** * Created by SummerGao on 16-11-7. */ layui.use('upload', function () { var upload = layui.upload; $(document).on('change', '.upload', function () { //上傳介面 var url = uploadServerPathWeChat+ "file/upload/receipt/receipt/receipt?isWeChat=1"; //執行例項 upload.render({ elem: '#' + $(this).attr('id')//繫結元素 , url: url , accept: 'images' , multiple: false , auto: false , bindAction: '#fileUploadAction' , before: function (obj) { lay.msg("檔案上傳中....") } , done: function (res) { //上傳完畢回撥 } , error: function () { //請求異常回調 } }); //滑鼠點選事件執行附件上傳操作 $("#fileUploadAction").click(); }); });
關鍵程式碼:
$(document).on('change', '.upload', function () {
});
如果你的是下面這種寫法會不起作用
$(".upload").on('change', function () {
});
>> $(".upload").on('change', 只能為頁面現有的元素繫結點選事件,如果是動態生成的新的元素,是沒有事件的
>> 而$(document).on('change', "指定的元素",function(){});方法則是將指定的事件繫結在document上,而新產生的元素如果符合指定的元素,