jQuery-select2 官方文档笔记(一)——基础应用

select2官网:https://select2.org/

一、上手

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)

可取值:

ValueDescription
'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 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远程数据(*)

详见本博客另一篇博文:
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 @ 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...";
  }
}
  • 17
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值