search
HomeWeb Front-endHTML TutorialJS组件系列--Bootstrap Select2组件使用小结_html/css_WEB-ITnose

前言:在介绍select组件的时候,博主之前分享过一篇 JS组件系列——两种bootstrap multiselect组件大比拼 ,这两个组件的功能确实很强大,只可惜没有图文结合的效果(也就是将图片放入到select里面随着文字一起显示)。前两天做一个菜单图标选择的功能,就要用到这个图文选择的功能。于是乎又是找啊找。终于不负所望,找到了我们伟大的select2组件。今天分享下这个组件的一些用法和特性。

一、组件说明以及API说明

Select2使用示例地址: https://select2.github.io/examples.html

Select2参数文档说明: https://select2.github.io/options.html

Select2源码: https://github.com/select2/select2

二、组件特性效果展示

一些通用的单选、多选、分组等功能这里就不多做介绍了,multiselect这方面是强项。重点介绍下select2的一些特性效果:

1、多选效果

可以设置最多只能选几个

2、图文结合的效果

3、远程搜索功能(即在用户输入搜索内容时动态去后台取数据)

输入内容前

输入空格搜索出全部

滚动条滑动到底部自动加载剩余项

输入文本动态去后台过滤

更高级的用法如:

其实使用起来也不难,就是一个拼html的过程。

三、代码示例

1、多选效果

select2的多选很简单,设置一个属性就好了。

   <script src="~/Scripts/jquery-1.10.2.js"></script>    <script src="~/Content/bootstrap/js/bootstrap.js"></script>    <link href="~/Content/bootstrap/css/bootstrap.css" rel="stylesheet" />    <script src="~/Content/select2-master/dist/js/select2.js"></script>    <link href="~/Content/select2-master/dist/css/select2.css" rel="stylesheet" />
  <select id="sel_menu2" multiple="multiple" class="form-control">         <optgroup label="系统设置">              <option value="1">用户管理</option>              <option value="2">角色管理</option>              <option value="3">部门管理</option>              <option value="4">菜单管理</option>         </optgroup>         <optgroup label="订单管理">              <option value="5">订单查询</option>              <option value="6">订单导入</option>              <option value="7">订单删除</option>              <option value="8">订单撤销</option>         </optgroup>         <optgroup label="基础数据">              <option value="9">基础数据维护</option>          </optgroup>     </select>
    //多选    $("#sel_menu2").select2({        tags: true,        maximumSelectionLength: 3  //最多能够选择的个数    });

2、图文结合的效果

<select id="sel_menu" class="js-example-templating js-states form-control">             <optgroup label="系统设置">                 <option value="1">用户管理</option>                 <option value="2">角色管理</option>                 <option value="3">部门管理</option>                 <option value="4">菜单管理</option>             </optgroup>             <optgroup label="订单管理">                 <option value="5">订单查询</option>                 <option value="6">订单导入</option>                 <option value="7">订单删除</option>                 <option value="8">订单撤销</option>             </optgroup>             <optgroup label="基础数据">                 <option value="9">基础数据维护</option>             </optgroup>         </select>
$(function () {    //带图片    $("#sel_menu").select2({        templateResult: formatState,        templateSelection: formatState    });});function formatState(state) {    if (!state.id) { return state.text; }    var $state = $(      '<span><img  src="/content/images/' + state.element.value.toLowerCase() + '.ico" class="img-flag" / alt="JS组件系列--Bootstrap Select2组件使用小结_html/css_WEB-ITnose" > ' + state.text + '</span>'    );    return $state;};

3、远程搜索功能(即在用户输入搜索内容时动态去后台取数据)

 <select id="sel_menu3" class="js-data-example-ajax form-control">      <option value="3620194" selected="selected">请选择</option> </select>
$(function () {    //远程筛选    $("#sel_menu3").select2({        ajax: {            url: "/Home/GetProvinces",            dataType: 'json',            delay: 250,            data: function (params) {                return {                    q: params.term, // search term                    page: params.page                };            },            processResults: function (data, params) {                params.page = params.page || 1;                return {                    results: data.items,                    pagination: {                        more: (params.page * 10) < data.total_count                    }                };            },            cache: true        },        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work        minimumInputLength: 1,        templateResult: formatRepoProvince, // omitted for brevity, see the source of this page        templateSelection: formatRepoProvince // omitted for brevity, see the source of this page    });});
function formatRepoProvince(repo) {    if (repo.loading) return repo.text;    var markup = "<div>"+repo.name+"</div>";    return markup;}

这里有要注意的一个地方就是processResults属性对应的方法有一个more属性用于是否分页显示的,这里的值要和你需要一次显示的值的条数匹配。

后台对应的方法如下:

public List<string> lstProvince = new List<string>() {"北京市","天津市","重庆市","上海市","河北省","山西省","辽宁省","吉林省","黑龙江省","江苏省","浙江省","安徽省","福建省","江西省","山东省","河南省","湖北省","湖南省","广东省","海南省","四川省","贵州省","云南省","陕西省","甘肃省","青海省","台湾省","内蒙古自治区","广西壮族自治区","西藏自治区","宁夏回族自治区","新疆维吾尔自治区","香港特别行政区","澳门特别行政区" };        public JsonResult GetProvinces(string q, string page)         {            var lstRes = new List<Province>();            for (var i = 0; i < 30; i++)            {                var oProvince = new Province();                oProvince.id = i;                oProvince.name = lstProvince[i];                lstRes.Add(oProvince);            }            if (!string.IsNullOrEmpty(q.Trim()))            {                lstRes = lstRes.Where(x => x.name.Contains(q)).ToList();            }            var lstCurPageRes = string.IsNullOrEmpty(page) ? lstRes.Take(10) : lstRes.Skip(Convert.ToInt32(page) * 10 - 10).Take(10);            return Json(new { items = lstCurPageRes, total_count = lstRes.Count }, JsonRequestBehavior.AllowGet);        }
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between an HTML tag and an HTML attribute?What is the difference between an HTML tag and an HTML attribute?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools