这篇文章主要为大家详细介绍了基于jquery实现多选下拉列表,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了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">
<p class="width150">
可多选年份:<input type="text" id="yearinput" placeholder="请选择年份" readonly>
<ul id="yearid" class="hide">
</ul>
</p>
</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>
效果图:
以上就是使用jquery实现下拉列表选项的详细内容。