jQuery-select2 官方文档笔记(一)——基础应用 迷南。 2022-05-16 08:52 538阅读 0赞 > select2官网:https://select2.org/ ### 文章目录 ### * * * 一、上手 * * * 1. CDN * 2. 单选select * 3. 多选select * 4. 禁用状态 * 5. 宽度(width) * 6. 关于选项(Options) * 7. Placeholders * 二、Data Sources * * * 1. select2数据源格式要求 * 2. 在数据源中标明预选中(\`"selected": true\`)和禁用状态(\`"disabled": true\`) * 3. 把数据转换为要求的格式 * 4. 分组数据 * 5. \[Ajax远程数据(\*)\](https://blog.csdn.net/fukaiit/article/details/81750755) * 6. local Arrays数据源 * 三、下拉框中列表的样式和行为(Dropdown) * * * 1. 自定义样式 * 2. 设置选择后不自动关闭列表 * 3. select2 append的位置 * 4. 使用\`templateSelection \`自定义列表样式 * 5. 多选列表限制选择个数(maximumSelectionLength) * 6. 快速清空已选项(allowClear) * 7. 可选同时允许用户自行输入(tags) * 四、国际化 ### 一、上手 ### ##### 1. CDN ##### <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <script type="text/javascript" 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> ##### 2. 单选select ##### $('.js-example-basic-single').select2(); ##### 3. 多选select ##### (1)select标签上添加`multiple="multiple"`属性 (2)召唤select2方法 $('.js-example-basic-multiple').select2(); ##### 4. 禁用状态 ##### 方法1:html中设置`<select>`的`disabled`的属性为true 方法2:`$(".js-example-disabled").prop("disabled", true);` ##### 5. 宽度(width) ##### 可取值: <table> <thead> <tr> <th>Value</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>'element'</code></td> <td>Uses the computed element width from any applicable CSS rules.</td> </tr> <tr> <td><code>'style'</code></td> <td>Width is determined from the select element’s style attribute. If no style attribute is found, null is returned as the width.</td> </tr> <tr> <td><code>'resolve'</code></td> <td>Uses the style attribute value if available, falling back to the computed element with as necessary.</td> </tr> <tr> <td><code>'<value>'</code>(具体数值)</td> <td>Valid CSS values can be passed as a string (e.g. width: ‘80%’).</td> </tr> </tbody> </table> ##### 6. 关于选项(Options) ##### 禁用单个选项的方法:在`<option>`标签上添加`disabled="disabled"` <select class="js-example-disabled-results"> <option value="one">First</option> <option value="two" disabled="disabled">Second (disabled)</option> <option value="three">Third</option> </select> ##### 7. Placeholders ##### $(".js-example-placeholder-single").select2({ placeholder: "Select a state" }); **注意:** 对于单选来说,必须在select的第一个位置设置一个空的option选项,placeholder才会起作用,否则浏览器会去选择第一个值。而多选是不能有空的option的。 Alternatively:the value of the placeholder option can be a data object representing a default selection. $('select').select2({ placeholder: { id: '-1', // the value of the option text: 'Select an option' } }); ### 二、Data Sources ### ##### 1. select2数据源格式要求 ##### 数据源由一个json对象表示; 具体的数据为一个key为results的对象数组,每一个对象必须至少包括id和text; pagination表示分页相关的设置; { "results": [ { "id": 1, "text": "Option 1" }, { "id": 2, "text": "Option 2" } ], "pagination": { "more": true } } ##### 2. 在数据源中标明预选中(`"selected": true`)和禁用状态(`"disabled": true`) ##### { "results": [ { "id": 1, "text": "Option 1" }, { "id": 2, "text": "Option 2", "selected": true }, { "id": 3, "text": "Option 3", "disabled": true } ] } ##### 3. 把数据转换为要求的格式 ##### select2必须要求有id和text属性,如果你在服务端无法做到包含id,或者API无法改变的情况下,你可以在把data传给select2之前做如下转换: **id:** var data = $.map(yourArrayData, function (obj) { obj.id = obj.id || obj.pk; // replace pk with your identifier return obj; }); **text:** var data = $.map(yourArrayData, function (obj) { obj.text = obj.text || obj.name; // replace name with the property used for the text return obj; }); ##### 4. 分组数据 ##### 每个组用`children` key来表示,组名用`text` property表示: { "results": [ { "text": "Group 1", "children" : [ { "id": 1, "text": "Option 1.1" }, { "id": 2, "text": "Option 1.2" } ] }, { "text": "Group 2", "children" : [ { "id": 3, "text": "Option 2.1" }, { "id": 4, "text": "Option 2.2" } ] } ], "paginate": { "more": true } } ##### 5. [Ajax远程数据(\*)][Ajax] ##### 详见本博客另一篇博文: [jQuery-select2通过ajax请求获取远端数据][Ajax] ##### 6. local Arrays数据源 ##### var data = [ { id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' } ]; $(".js-example-data-array").select2({ data: data }) ### 三、下拉框中列表的样式和行为(Dropdown) ### ##### 1. 自定义样式 ##### 可以通过templateResult 选项来设置下拉框显示的样式: function formatState (state) { if (!state.id) { return state.text; } var baseUrl = "/user/pages/images/flags"; var $state = $( '<span><img src="' + baseUrl + '/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>' ); return $state; }; $(".js-example-templating").select2({ templateResult: formatState }); 默认情况下,认为templateResult方法返回是纯字符串,会经过escapeMarkup方法去除html标记。如果需要用到返回的html标签,必须把templateResult方法返回的结包含在一个jquery对象中【[链接][Link 1]】。 ##### 2. 设置选择后不自动关闭列表 ##### 默认情况下,选择一项后,dropdown会自动关闭,通过如下设置可强制选择后不自动关闭列表,注意只对multiple select起作用。 $('#mySelect2').select2({ closeOnSelect: false }); ##### 3. select2 append的位置 ##### 默认情况下,select2会attach到body的结尾,并绝对定位,The `dropdownParent` option allows you to pick an alternative element for the dropdown to be appended to: $('#mySelect2').select2({ dropdownParent: $('#myModal') }); **select2的下拉列表在BootStrap的modal中显示有问题的说明:** [Select2 does not function properly when I use it inside a Bootstrap modal.][] 解决办法如上。 ##### 4. 使用`templateSelection`自定义列表样式 ##### 前面【二.5】ajax远程数据中说明过可以对ajax请求回来的数据进行自定义样式。 其实可以对数据源(html中、array、ajax)的数据自定义显示样式。 使用`templateSelection`自定义列表样式: function formatState (state) { if (!state.id) { return state.text; } var baseUrl = "/user/pages/images/flags"; var $state = $( '<span><img src="' + baseUrl + '/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>' ); return $state; }; $(".js-example-templating").select2({ templateSelection: formatState }); ##### 5. 多选列表限制选择个数(maximumSelectionLength) ##### $(".js-example-basic-multiple-limit").select2({ maximumSelectionLength: 2 }); ##### 6. 快速清空已选项(allowClear) ##### 设置allowClear为true,将会在select后加一个X号,可用于快速清空已选项。 $('select').select2({ allowClear: true }); ##### 7. 可选同时允许用户自行输入(tags) ##### 同时适用于单选和多选的情况: $(".js-example-tags").select2({ tags: true }); 通过createTag 方法可给新增加的tags添加额外的属性: $('select').select2({ createTag: function (params) { var term = $.trim(params.term); if (term === '') { return null; } return { id: term, text: term, newTag: true // add additional parameters } } }); 也可以通过该方法对用户自己输入的值进行合法性检验: $('select').select2({ createTag: function (params) { // Don't offset to create a tag if there is no @ symbol if (params.term.indexOf('@') === -1) { // Return null to disable tag creation return null; } return { id: params.term, text: params.term } } }); 可以通过`insertTag`设定新增tag的位置: $('select').select2({ insertTag: function (data, tag) { // Insert the tag at the end of the results data.push(tag); } }); ### 四、国际化 ### 需要在引入select2的后面引入语言包 $(".js-example-language").select2({ language: "es" }); 在select的父元素中定义`lang="es"`也会起作用。 自定义提示文字: language: { // You can find all of the options in the language files provided in the // build. They all must be functions that return the string that should be // displayed. inputTooShort: function () { return "You must enter more characters..."; } } [Ajax]: https://blog.csdn.net/fukaiit/article/details/81750755 [Link 1]: https://select2.org/dropdown#built-in-escaping [Select2 does not function properly when I use it inside a Bootstrap modal.]: https://select2.org/troubleshooting/common-problems#select2-does-not-function-properly-when-i-use-it-inside-a-bootst
还没有评论,来说两句吧...