selet2是一款input+selet结合的组件,是最好的搜索下拉框,没有之一。原因是别的没有,只有它这么一家,你没得选择。正如有人说它‘Select2不是特别好用,但又找不到比它更好的下拉框插件。’
网上对它的介绍零零碎碎,又不是特别的全面,下边我就总结了一番
单选
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="plugs/select2/css/select2.min.css" /> <style> .mysel{width: 100px;} button{margin-top: 10px; display: block;} </style> </head> <body> <select class="mysel"></select> <button>取值</button> <script src="plugs/jquery-3.2.1.min.js" ></script> <script src="plugs/select2/js/select2.full.min.js" ></script> <script src="plugs/select2/js/i18n/zh-CN.js" ></script> <script type="text/javascript"> //后端返回的数据 var data = [ {id:123,text:"张三",say:"呵呵"}, {id:234,text:"李四",say:"中国"}, {id:345,text:"wang",say:"你懂个屁"}, {id:456,text:"张老大",say:"okok"} ]; $(".mysel").select2({ data: data, placeholder:‘请选择‘, allowClear:true, language: ‘zh-CN‘ }) $("button").click(function(){ var res=$(".mysel").select2("data"); console.log(res[0])//获取选中项 console.log($(".mysel").val())//获取选中的值(id) //tip:推荐使用第一种获取值的返回数组,单选就取res[0];好处是不进可以获取id、text还可以获取其他属性,如res[0].say }) </script> </body> </html>
多选
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="plugs/select2/css/select2.min.css" /> <style> .mysel{width: 200px;} button{margin-top: 10px; display: block;} </style> </head> <body> <select class="mysel"></select> <button>取值</button> <script src="plugs/jquery-3.2.1.min.js" ></script> <script src="plugs/select2/js/select2.full.min.js" ></script> <script src="plugs/select2/js/i18n/zh-CN.js" ></script> <script type="text/javascript"> //后端返回的数据 var data = [ {id:123,text:"张三",say:"呵呵"}, {id:234,text:"李四",say:"中国"}, {id:345,text:"wang",say:"你懂个屁"}, {id:456,text:"张老大",say:"okok"} ]; $(".mysel").select2({ data: data, placeholder:‘请选择‘, allowClear:true, language: ‘zh-CN‘, multiple: true }) $("button").click(function(){ var res=$(".mysel").select2("data"); console.log(res)//获取选中项 console.log($(".mysel").val())//获取选中的值(id) //tip:推荐使用第一种获取值的返回数组,单选就取res[0];好处是不进可以获取id、text还可以获取其他属性,如res[0].say }) </script> </body> </html>
时间: 2024-11-10 17:25:05