layui之select的option叠加问题的解决方法

发布时间:2020-10-07 22:42:39 作者:小飞博客
来源:脚本之家 阅读:179

小编我在使用layui,在select的地方遇到了坑,select里的值居然无法清空,select里的option还有叠加问题,为了解决这个问题,也达到我的功能,我研究了下,让有同样需求的小伙伴不踩坑,特贴上我的源码:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>layui-下拉框联动测试</title>
 <link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" >
</head>
<body>
<div id="wrap">
 <div class="layui-form" lay-filter="merchantForm">
 <div class="layui-form-item">
 <label class="layui-form-label">选择框</label>
 <div class="layui-input-block">
  <select name="city" lay-verify="required" id="test1" lay-filter="test1">
  <option value="0">时间</option>
  <option value="1">金额</option>
  </select>
 </div>
 </div>
 <div class="layui-form-item">
 <label class="layui-form-label">选择框</label>
 <div class="layui-input-block">
  <select name="city" lay-verify="required" id="test2" lay-filter="test2">
  <option value="">请选择规则名称</option>
  </select>
 </div>
 </div>
</div> 
<button id="btn">确定</button>
</body>
<script src="layui/layui.all.js"></script>
<script src="layui/jquery-1.8.3.min.js"></script>
<script>
//后台传过来的数据
var data=[
 {unitType:0,ruleName:'时间规则11',amount:1100,money:1100},
 {unitType:0,ruleName:'时间规则12',amount:1200,money:1200},
 {unitType:0,ruleName:'时间规则13',amount:1300,money:1300},
 {unitType:1,ruleName:'金额规则21',amount:2100,money:2100},
 {unitType:1,ruleName:'金额规则22',amount:2200,money:2200},
 {unitType:1,ruleName:'金额规则23',amount:2300,money:2300},
];
//初始化默认为时间类型以及对应的时间规则
layui.use('form', function(){
 var form = layui.form;
  $('#test2').html('');
  var html='';
  $.each(data,function(i,e){
   if(e.unitType==0)
    html+=`<option data-type="${e.unitType}">${e.ruleName}</option>`;
  })
  $('#test2').append(html);
  form.render('select'); 
})
//动态二级联动
layui.use('form', function(){
 var form = layui.form;
  form.on('select(test1)', function(obj){
  $('#test2').html('');
  var html='';
  if(obj.value==0){
   $.each(data,function(i,e){
    if(e.unitType==obj.value)
     html+=`<option data-type="${e.unitType}">${e.ruleName}</option>`;
   })
   $('#test2').append(html);
  }else if(obj.value==1){
   $.each(data,function(i,e){
    if(e.unitType==obj.value)
    html+=`<option data-type="${e.unitType}">${e.ruleName}</option>`;
   })
   $('#test2').append(html);
  }
  form.render('select');
 });
})
//二级联动完毕后获取对应的规则数据
$('#btn').click(function(){
 var thisValue=data.find((v)=>v.ruleName==$('#test2').val());
 console.log(thisValue); 
})
</script>
</html>

以上这篇layui之select的option叠加问题的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

推荐阅读:
  1. 记录-select option 切换展示不同选项
  2. jQuery添加/删除Select的Option项:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

layui select option

上一篇:关于Python3 lambda函数的深入浅出

下一篇:Centos7 安装Nginx整合Lua的示例代码

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》