首先,这是一个坑,大坑,网上一大堆写的云里雾里,不知所以,转了一圈,除了copy就是copy,Jesus God,花了一晚上,走通了这个坑,话不多说,直接解决
layui版本: layui-v2.5.6
jquery版本:jQuery v3.2.1
问题:
上传多个商品的时候,后续的表单需要动态生成,其中包括上传文件按钮,获取文件。可是动态上传后,改上传按钮没有作用。我不是专业的前端,没有深入分析,直接说明解决方法,至于原理啥的,如果帮助了你,麻烦告知。
点击增加的时候,动态生成表单
具体做法,首先,动态生成的id需要动态拼接,保持唯一性,在拼接完成后,重新将upliad.render(...)的所有逻辑调用一遍。期间元素选择用id,这个很重要!!!!
封装成方法:
function uploadImgRender(e,showImg,uploadimd){ var uploadImg = upload.render({ elem: e , url: '' //改成您自己的上传接口 , before: function (obj) { //预读本地文件示例,不支持ie8 obj.preview(function (index, file, result) { console.log(uploadImg); $(showImg).attr('src', result); //图片链接(base64) }); } , done: function (res) { //如果上传失败 if (res.error > 0) { return layer.msg('上传失败'); } //上传成功 if (res.error == 0) { console.log(uploadImg) $(uploadimd).html(res.url); return layer.msg('上传成功'); } } , error: function () { //演示失败状态,并实现重传 var demoText = $('#demoText'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'); demoText.find('.demo-reload').on('click', function () { uploadImg.upload(); }); } });
动态生成后点击:
HTML增加按钮: <button class="layui-btn" type="button" id="addSpecification" data-type="addMM">增加</button> js: var count = 1; var addM = { addMM: function () { count += 1; var newInput ="<hr/><div class="layui-form-item"> " + " <label for="phone" class="layui-form-label"> " + " <span class="x-red"></span>商品图片</label> " + " <div class="layui-upload"> " + " <button type="button" class="layui-btn imgUpload_" data-type="imgUpload_R" id="imgUpload_"+count+"">上传图片</button> " + " <div class="layui-word-aux"> " + " <span class="x-red">*</span>单图上传,尺寸建议750x750 " + " </div> " + " </div> " + " </div> " + " <div class="layui-form-item"> " + " <label for="phone" class="layui-form-label"> " + " <span class="x-red"></span></label> " + " <div class="layui-upload-list"> " + " <img class="layui-upload-img" id="imgUpload_"+count+"_"> " <p id="imgUpload_goods_"+count+""></p> " + " </div> " + " </div> " ; $('#multipleSpecifications').append(newInput); //这个很重要。虽然冗余了,但是木有办法 uploadImgRender("#imgUpload_"+count,"#imgUpload_"+count+"_","#imgUpload_goods_"+count); } }; //动态加载元素用 $('#addSpecification').on('click', function () { var othis = $(this), type = othis.data('type'); addM[type] ? addM[type].call(this, othis) : ''; });