地址:https://harvesthq.github.io/chosen/
效果:
因为只需要这个功能,就只研究这个功能了,代码:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Chosen: A jQuery Plugin by Harvest to Tame Unwieldy Select Boxes</title> <!-- <link rel="stylesheet" href="docsupport/style.css"> --> <!-- <link rel="stylesheet" href="docsupport/prism.css"> --> <link rel="stylesheet" href="chosen.css"> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://ajax.googleapis.com; style-src 'self'; img-src 'self' data:"> </head> <body> <form> <em>Into This</em> <select data-placeholder="Choose a Country..." class="chosen-select" multiple tabindex="4"> <option value=""></option> <option value="United States">United States</option> <option value="United Kingdom">United Kingdom</option> <option value="Afghanistan">Afghanistan</option> <option value="Aland Islands">Aland Islands</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="American Samoa">American Samoa</option> <option value="Andorra">Andorra</option> <option value="Angola">Angola</option> </select> <script src="docsupport/jquery-3.2.1.min.js" type="text/javascript"></script> <script src="chosen.jquery.js" type="text/javascript"></script> <script src="docsupport/prism.js" type="text/javascript" charset="utf-8"></script> <script src="docsupport/init.js" type="text/javascript" charset="utf-8"></script> </form> </body> </html>
以上js和css都要引入才可以
如果select的option是动态生成的 如:
function getzhr() { jQuery.support.cors = true;//ie请求数据 $.ajax({ url:‘’', type: 'post', async: true, data: {}, dataType: 'json', success: function (res) { if (!res['MSG']) { tbzhr = res['data']; if(!tbzhr){} else{ var zhroption=''; $(".chosen-select").html(""); for(var i=0;i<tbzhr.length;i++){ zhroption+='<option value="'+tbzhr[i]['name']+'">'+tbzhr[i]['name']+'</option>'; } $(".chosen-select").append(zhroption); $(".chosen-select").trigger("chosen:updated"); $(".chosen-container").attr("style"," min- 400px;max-550px;"); } } }, error: function (res) { } }); }
因为引入了以后发现生成的宽度始终是0,所以加载完了以后重新设置了宽度(注意如果需要图标,需要修改chosen.css 对应图标路径):
如果select是动态生成的,
$(".chosen-select").chosen();//需要先初始化
$(".chosen-select").append(zhroption) ;//然后再赋值
$(".chosen-select").trigger("chosen:updated");
$(".chosen-container").attr("style", " 100%");