jQuery-select2 官方文档笔记(一)——基础应用
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)
可取值:
Value | Description |
---|---|
'element'
|
Uses the computed element width from any applicable CSS rules. |
'style'
|
Width is determined from the select element’s style attribute. If no style attribute is found, null is returned as the width. |
'resolve'
|
Uses the style attribute value if available, falling back to the computed element with as necessary. |
'<value>' (具体数值)
|
Valid CSS values can be passed as a string (e.g. width: ‘80%’). |
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 optiontext: '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 identifierreturn obj;
});
text:
var data = $.map(yourArrayData, function (obj) {obj.text = obj.text || obj.name; // replace name with the property used for the textreturn 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远程数据(*)
详见本博客另一篇博文:
jQuery-select2通过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对象中【链接】。
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 @ symbolif (params.term.indexOf('@') === -1) {// Return null to disable tag creationreturn null;}return {id: params.term,text: params.term}}
});
可以通过insertTag
设定新增tag的位置:
$('select').select2({insertTag: function (data, tag) {// Insert the tag at the end of the resultsdata.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...";}
}
jQuery-select2 官方文档笔记(一)——基础应用相关推荐
- 【goldengate】官方文档笔记三 Oracle GoldenGate 实时报表
这篇文档循序渐进的讲述了OGG在适时复制的几种配置方案.从最基本的配置开始讲起,逐渐加入新的进程,加入新的策略,配置也随之改变.下面从最基础的配置说起. 报表配置 一对一复制是OGG最基本的配置方案: ...
- 【goldengate】官方文档笔记四 Oracle GoldenGate实时数据分布
数据分布配置是一对多得配置方案.OGG支持将源库同步到多个目标系统. 数据分布配置需要注意事项: 如果数据传输过程中,投递进程(data pump)发现目标库网络连接出现故障,捕获到得数据会继续像其它 ...
- jQuery-select2 官方文档笔记(二)——较高级应用
select2官网:https://select2.org/ 一.Search 1. matcher 2. 分组matcher 3. 设置最短最长搜索词组长度(minimumInputLength & ...
- carla官方文档笔记1
介绍 介绍 CARLA是一个开源的自动驾驶模拟器.它是从零开始构建的,作为一个模块化和灵活的API来解决一系列涉及到自动驾驶问题的任务.carla的主要目标之一是帮助实现自主驾驶研发的灵活化,作为一种 ...
- Unity官方文档笔记(一)在Unity中操作
前言:本系列文档基于Unity 2019.4版本进行整理 一 系统要求 1.1 Unity Editor Windows 需要Win7(SP1+)及以上系统,仅限64位版本:CPU要求X64架构:GP ...
- Xamarin 总结 (官方文档笔记)
1. ContentDescription 一个 属性,供屏幕读取 API 使用,以提供控件用途的可访问说明. <ImageButtonandroid:id=@+id/saveButton&qu ...
- python3 scrapy中文文档_Scrapy官方文档笔记
1.创建Scrapy项目 首先用cmd命令行去操作,输入 scrapy startproject 项目名 #这里输入的项目名,就是在你输入的目录它会建立一个新的文件夹,这个文件夹里面还是同样名字的一个 ...
- python 笔记 :Gym库 (官方文档笔记)
Gym是一个开发和比较强化学习算法的工具箱.它不依赖强化学习算法结构,并且可以使用很多方法对它进行调用. 1 Gym环境 这是一个让某种小游戏运行的简单例子. 这将运行 CartPole-v0 环境实 ...
- Spring Framework Integration 官方文档笔记
Integration Message Conversion WebMvcConfigurationSupport 内含默认的 Converter BufferedImageHttpMessageCo ...
最新文章
- excplise tomcat启动过程中类找不到
- C# 数据库连接笔记
- php双向通信,RSA + AES 双向通信加密
- 3600插b450i开不了机_win10电脑开不了机怎么办
- python3.6.0安装教程-centos6.9安装python3.6.0和模块
- html app的登陆、注册,登陆_注册.html
- VB中判断空的几种方法,Null, Missing, Empty, Nothing, vbNullString区别
- 生产订单修改记录的跟踪方法!
- python视图函数是什么_python之视图函数(views.py)
- html5控制单片机,10.2 单片机中 PWM 的原理与控制程序
- 2.30mongodb创建集合,数据管理2.31PHP的mongdb扩展
- [bug]微信小程序使用 scroll-view 和 box-shadow 引起页面抖动
- 多目标跟踪全解析,全网最全
- Vc中对话框数据交换和验证机制
- 毕设题目:Matlab图像去噪
- 金蝶kis是怎么恢复套账的
- ACM退役帖(青岛赛后再更新)
- 弘辽科技:拒做“淘宝客”,可小红书的电商梦何以撑未来?
- 山东大学项目实训——地图圈系统——微信小程序(18)
- 黑马程序员——Java的代理模式
热门文章
- android教程pdf!2021Android高级面试题面试题,吐血整理
- 2264: sequence
- java抽象语法树_抽象语法树(AST)
- GStreamer功能详解
- 图像分割 - 阈值处理 - 最大类间方差法(OTSU)
- JAVA(4)学习笔记:JVM虚拟机上的栈、大驼峰命名法和小驼峰命名法、实参和形参、重载方法、调用栈、递归练习(汉诺塔+斐波那契数列)、数组的定义、数组的初始化、增强for循环。
- Day 30 - 实作 Amazon API GateWay 整合 AWS Lambda 与 Dynamodb
- 采购协议、合同的审核及下达
- hd live tv android,HD Live TV
- GitHub创建本地分支并且和GitHub远程分支建立关系