下拉框、下拉控件Select2的使用
程序员文章站
2023-12-28 13:37:52
...
直接新建html文档即可用
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>select2</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body>
<select id="select2_id" multiple="multiple">
<option value="kakaxi">卡卡西</option>
<option value="mingren">鸣人</option>
<option value="zuozhu">佐助</option>
<option value="xiaoying">小樱</option>
<option value="bofengshuimen">波风水门</option>
<option value="dashewan">大蛇丸</option>
<option value="gangshou">纲手</option>
<option value="zilaiye">自来也</option>
</select>
<button id="getBtn">获取选中值</button>
<button id="destoryBtn">移除下拉框</button>
<button id="initBtn">加载下拉框</button>
<button id="addBtn">添加值</button>
<button id="emptyBtn">清空下拉框</button>
<button id="setBtn1">单赋值</button>
<button id="setBtn2">多赋值</button>
<button id="setBtn3">选中所有</button>
<script type="text/javascript">
$(function(){
initSelect2();
$("#getBtn").on('click', function(){
alert($("#select2_id").val());
});
$("#addBtn").on('click', function(){
$("#select2_id").append($("<option>", {value: 'value1', text: 'text1'}));
});
$("#destoryBtn").on('click', function(){
$("#select2_id").select2("destroy");
});
$("#emptyBtn").on('click', function(){
$("#select2_id").empty();
});
$("#initBtn").on('click', function(){
initSelect2();
});
$("#setBtn1").on('click', function(){
// 赋值 - 单选
$("#select2_id").val('xiaoying').trigger("change");
});
$("#setBtn2").on('click', function(){
// 赋值 - 多选
$("#select2_id").val(['kakaxi','gangshou']).trigger("change");
});
$("#setBtn3").on('click', function(){
$("#select2_id")
.val($("#select2_id option")
.map(function(){
return $(this).val();
}).get()
).trigger("change");
});
});
function initSelect2() {
$('#select2_id').select2({
//placeholder: "请选择",
placeholder: {id: '', text: "请选择"}, // 同上,这里默认空值为 ''
tags:true,
createTag:function (decorated, params) {
return null;
},
width:'400px',
closeOnSelect: true,
allowClear: true,
language: "zh-CN"
//tokenSeparators: [',', ' ']
});
}
</script>
</body>
</html>
select2事件
$('select[name="level1"]').on("change",function(e){ console.log("我改变了")});
$('select[name="level1"]').on("select2:open",function(e){ console.log("我打开了")});
$('select[name="level1"]').on("select2:close",function(e){ console.log("我关闭了")});
$('select[name="level1"]').on("select2:select",function(e){ console.log("我选中了")});
$('select[name="level1"]').on("select2:unselect",function(e){ console.log("我取消了")});