小编我在使用layui,在select的地方遇到了坑,select里的值居然无法清空,select里的option还有叠加问题,为了解决这个问题,也达到我的功能,我研究了下,让有同样需求的小伙伴不踩坑,特贴上我的源码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>layui前端框架select联动</title> 6 <link rel="stylesheet" href="./layui/css/layui.css"> 7 </head> 8 <body> 9 <div id="wrap"> 10 <div class="layui-form"> 11 <div class="layui-form-item"> 12 <label class="layui-form-label">选择框</label> 13 <div class="layui-input-block"> 14 <select name="city" lay-verify="required" id="test1" lay-filter="test1"> 15 <option value="">请选择账号类型</option> 16 <option value="0">时间</option> 17 <option value="1">金额</option> 18 </select> 19 </div> 20 </div> 21 <div class="layui-form-item"> 22 <label class="layui-form-label">选择框</label> 23 <div class="layui-input-block"> 24 <select name="city" lay-verify="required" id="test2" lay-filter="test2"> 25 <option value="">请选择规则名称</option> 26 </select> 27 </div> 28 </div> 29 </div> 30 </body> 31 <script src="./layui/layui.js"></script> 32 <script src="./layui/layer/layer.js"></script> 33 <script src="jquery-1.8.3.min.js"></script> 34 <script> 35 //后台传过来的数据 36 var data=[ 37 {unitType:0,ruleName:‘时间规则11‘,amount:1100,money:1100}, 38 {unitType:0,ruleName:‘时间规则12‘,amount:1200,money:1200}, 39 {unitType:0,ruleName:‘时间规则13‘,amount:1300,money:1300}, 40 {unitType:1,ruleName:‘金额规则21‘,amount:2100,money:2100}, 41 {unitType:1,ruleName:‘金额规则22‘,amount:2200,money:2200}, 42 {unitType:1,ruleName:‘金额规则23‘,amount:2300,money:2300}, 43 ]; 44 layui.use(‘form‘, function(){ 45 var form = layui.form; 46 form.on(‘select(test1)‘, function(obj){ 47 if(obj.value==‘‘){ 48 return false; 49 }else if(obj.value==0){ 50 layui.use(‘form‘, function(){ 51 var form = layui.form; 52 $.each(data,function(i,e){ 53 var html=‘‘; 54 if(e.unitType==0){ 55 html+=`<option value="${e.unitType}" class="one">${e.ruleName}</option>`; 56 } 57 $(‘#test2‘).find(‘option.two‘).remove(); 58 $(‘#test2‘).append(html); 59 }) 60 form.render(‘select‘); 61 layui.use(‘form‘, function(){ 62 var form = layui.form; 63 form.on(‘select(test2)‘, function(obj){ 64 $(‘#test2 option‘).eq($(‘.one‘).size()+1).nextAll().remove(); 65 }) 66 }) 67 }) 68 }else{ 69 layui.use(‘form‘, function(){ 70 var form = layui.form; 71 $.each(data,function(i,e){ 72 var html=‘‘; 73 if(e.unitType==1){ 74 html+=`<option value="${e.unitType}" class="two">${e.ruleName}</option>`; 75 } 76 $(‘#test2‘).find(‘option.one‘).remove(); 77 $(‘#test2‘).append(html); 78 }) 79 form.render(‘select‘); 80 layui.use(‘form‘, function(){ 81 var form = layui.form; 82 form.on(‘select(test2)‘, function(obj){ 83 $(‘#test2 option‘).eq($(‘.two‘).size()+1).nextAll().remove(); 84 }) 85 }) 86 }) 87 } 88 }) 89 }); 90 </script> 91 </html>
有疑问的小伙伴可以留言给我,谢谢。
时间: 2024-11-07 19:17:46