视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
基于jquery实现多选下拉列表
2020-11-27 22:33:28 责编:小OO
文档


本文实例为大家分享了jquery实现多选下拉列表展示的具体代码,供大家参考,具体内容如下

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <style>
 ul li{
 list-style: none;
 }
 .hide{display: none}
 .width150{
 width: 150px;
 }
 .width150 input[type="text"]{
 width: 100%; 
 height: 32px; 
 border: 1px solid #ccc; 
 border-radius: 4px; 
 padding-left: 12px;
 }
 .width150 ul{ 
 width: 96%; 
 padding: 0 0 0 20px; 
 margin: 0; 
 border: 1px solid #ccc; 
 }
 .width150 li{ 
 padding: 5px; 
 }
 .width150 li+li{ 
 border-top: 1px solid #ccc; 
 }
 </style>
</head>
<body> 
 <form id="form"> 
 <div class="width150">
 可多选年份:<input type="text" id="yearInput" placeholder="请选择年份" readonly>
 <ul id="yearId" class="hide">
 </ul>
 </div>
 </form>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script>
 (function(){
 var str = '';
 var arr = {
 0 : {name:'2015',id:0},
 1 : {name:'2016',id:0},
 2 : {name:'2017',id:0}
 };
 for (let x in arr){
 console.info(x);
 str += `<li><label><input type="checkbox" value="${arr[x].id}" data-name="${arr[x].name}">${arr[x].name}</label></li>`;
 }
 $('#yearId').html(str);
 })();

 $("#yearInput").click(function(){
 $(this).attr('placeholder','');
 var name = '';
 $('#yearId input').each(function () {//循环遍历checkbox
 var check=$(this).is(':checked');//判断是否选中
 if(check){
 name += $(this).attr('data-name')+',';
 $(this).attr('name',"yearId");
 }else {
 $(this).attr('name',"");
 }
 });
 $("#yearInput").val(name.slice(0,-1));//去除最后的逗号
 });

 $("#yearId").mouseover(function() {
 if (!$("#yearId").hasClass('hover')){//类hover在下面用来验证是否需要隐藏下拉,没有其他用途。
 $("#yearId").addClass('hover');
 }
 }).mouseout(function(){
 $("#yearId").removeClass('hover');
 });

 $(document).on('click',function() {
 if (!$("#yearInput").is(":focus") && !$("#yearId").hasClass('hover')) {//如果没有选中输入框且下拉不在hover状态。
 var name = '';
 $('#yearId input').each(function () {//遍历checkbox
 var check = $(this).is(':checked');//判断是否选中
 if (check) {
 name += $(this).attr('data-name') + ',';
 $(this).attr('name', "yearId");
 } else {
 $(this).attr('name', "");
 }
 });
 $("#yearInput").val(name.slice(0, -1));//去除最后的逗号
 $("#yearId").addClass('hide');
 } else {
 $("#yearId").removeClass('hide');
 }
 });
</script>
</html>

效果图:

下载本文
显示全文
专题