学习笔记《Select2》

官方网站:https://select2.github.io/

这是一个很好用的jQuery插件,可以定制自己想要的select下拉框,支持搜索功能,标签multiple多选,Ajax请求远程数据等,只需要在头部引入如下两个文件:



下面是个简单的小例子:
HTML:


JS:


最近在使用的过程中前端页面效果还是很好的,能够实现想要的基本功能及效果。在前端页面加载的时候插件会隐藏原有的select下拉框,用span和ul、li重新呈现出select下拉框的效果,这时候单纯的页面效果已经达到了,但是往往伴随着表单的提交,那怎样获取被选中的值呢?由于原本的select下拉框已经被隐藏了,所以change、click等事件是触发不了的。官方提供了一些方法,如下所示:

change is fired whenever an option is selected or removed.
select2:open is fired whenever the dropdown is opened.
select2:opening is fired before this and can be prevented.
select2:close is fired whenever the dropdown is closed.
select2:closing is fired before this and can be prevented.
select2:select is fired whenever a result is selected.
select2:selecting is fired before this and can be prevented.
select2:unselect is fired whenever a result is unselected.
select2:unselecting is fired before this and can be prevented.

代码如下:

var $eventSelect=$(".example");
$eventSelect.on("select2:open",function(e){ log("select2:open",e); });
$eventSelect.on("select2:close",function(e){ log("select2:close",e); });
$eventSelect.on("select2:select",function(e){ log("select2:select",e); });
$eventSelect.on("select2:unselect",function(e){ log("select2:unselect",e); });
$eventSelect.on("change",function(e){ log("change"); });

有了这些方法就能更随心所欲地让我们的select框更好用。
更多心得待续。。。

你可能感兴趣的:(学习笔记《Select2》)