#Select2官网:可以在里面下载资源文件和进行样例参考
#https://select2.github.io/
#参考连接:
#https://segmentfault.com/a/1190000003795889
#http://blog.csdn.net/jiangeeq/article/details/52457351
#http://jingyan.baidu.com/article/59a015e35fb340f795886557.html
#需要引入的CSS和JS文件:
<link rel="stylesheet" href="<%=path%>/resources/bootstrap/css/bootstrap.css" >
<link rel="stylesheet" href="<%=path%>/resources/bootstrap/css/select2.min.css" >
<script src="<%=path%>/resources/bootstrap/js/select2.full.js"></script>
<script src="<%=path%>/resources/bootstrap/js/prettify.min.js"></script>
<script src="<%=path%>/resources/bootstrap/js/bootstrap.js"></script>
#实现被选中Item自动在下拉菜单中隐藏功能的CSS。
<style>
table td{word-break: keep-all;white-space:nowrap;}!important;
.select2-results__option[aria-selected=true] {
display: false;
}
li[aria-selected=true] {
display: none !important;
}
</style>
#html代码
<div id="USER_TAB" style="height:600px; width:1000px;">
<section id="tags" class="row">
<div class="col-md-4">
<p>
<select id= "city" class="select2-results__option form-control" multiple="multiple">
<option value = "ox" selected="selected">orange</option>
<option value = "wx">white</option>
<option value = "px" selected="selected">purple</option>
</select>
</p>
</div>
</section>
</div>
<script>
#初始化,tags和multiple必须设置;data是新加的Option。Option中的Id就是Value。
$("#city").select2({
tags: true,
multiple: true,
data: [{id: 'sx', text: 'story'},{id: 'bx', text: 'bug'},{id: 'tx', text: 'task'}] //这里是在原来的基础上添加,而不是覆盖
});
$("#city").on("select2:select",function(e){ #
console.log("select2:unselect", e.params.data.id); //新选择Option
e.params.data.disabled = true //让此元素之后不能被再选
console.log("select2:select text=", $("#city option:selected").text()); //获取所有选择Option的Text
console.log("select2:select text=", $(this).text()); //获取所有Option的Text
var element = e.params.data.element;
var $element = $(element);
element.hidden = true
$element.detach(); //删除此元素,与remove()一样
$(this).append($element);
$(this).trigger("change");
});
$("#city").on("select2:unselect",function(e){ //去除Option响应函数
var reslist=$(this).val(); //获取删除后的所有选中值系列
console.log("select2:unselect", e.params.data.id);获取被删除的Option的值
});
</script>