场景
使用layui前端框架,一个页面有多个时间控件,并且是动态添加,添加完成后,时间控件会出现闪退的情况,删除之后重新添加,不能重复渲染,点击不弹出日期选择弹窗
界面效果
完整代码
html代码
1 <div id="timeLimitGroup"> 2 <div class="layui-form-item"> 3 <div class="layui-inline" id="timeLimitDiv-1"> 4 <label class="layui-form-label">限时策略</label> 5 <div class="layui-input-inline" style="width:280px;"> 6 <input type="text" class="layui-input" name="timeLimit-1" id="timeLimit-1" readolny> 7 </div> 8 <div class="layui-input-inline" style="margin-top:8px;width: 10px;"> 9 <a href="javascript:;" onclick="addTimeLimit();return false;"><i class="layui-icon"></i></a> 10 </div> 11 </div> 13 </div> 14 </div>
js代码
1 var laydate = \'\'; 2 layui.use([\'form\', \'element\', \'layer\', \'jquery\', \'laydate\'], function () { 3 var form = layui.form, 4 laydate = layui.laydate; 5 laydate.render({ 6 elem: \'#timeLimit-1\' 7 , type: \'time\' 8 , range: true 9 ,trigger: \'click\' 10 }); 11 }); 12 function addTimeLimit() { 13 var obj = document.getElementById("timeLimitGroup"); 14 var newnode = document.createElement("div"); 15 var len = $("#timeLimitGroup").children().length; 16 newnode.innerHTML = \'<div class="layui-inline" id="timeLimitDiv-\' + (len + 1) + \'" style="margin-bottom:10px"><label class="layui-form-label"></label><div class="layui-input-inline" style="width:280px;margin-right: 10px;"><input type="text" class="layui-input" id="timeLimit-\' + (len + 1) + \'" name="timeLimit-\' + (len + 1) + \'" lay-key="\' + (len + 1) + \'" readolny></div><div class="layui-input-inline" style="margin-top:8px;width: 10px;"><a href="javascript:;" onclick="deleteTimeLimit(\' + (len + 1) + \');return false;"><i class="layui-icon"></i></a></div></div>\'; 17 obj.appendChild(newnode); 18 $(\'#timeLimit-\' + (len + 1)).removeAttr("lay-key"); 19 laydate.render({ 20 elem: \'#timeLimit-\' + (len + 1) 21 , type: \'time\' 22 , range: true 23 , lang: timelang 24 ,trigger: \'click\' 25 }); 26 } 27 function deleteTimeLimit(divID) { 28 $("#timeLimitDiv-" + divID).parent().remove(); 29 }
关键代码
1、添加属性 trigger: \'click\'
2、渲染之前清除上一次渲染的\'lay-key\' 属性
$(\'#timeLimit-\' + (len + 1)).removeAttr("lay-key");