Bootstrap实践之自动补全插件

Bootstrap
placeholder image
admin 发布于:2020-03-22 01:00:33
阅读:loading

基本介绍

Autocomplete自动补全插件也算是会经常用到的吧,写起来比较简单,早年间也写过好多的吧,但近年来主要是使用bootstrap模板做页面,按照老规矩把使用到的bootstrap风格的自动补全插件整理出来,用过的不多也就是本文所述的typeahead插件。

一般使用Autocomplete的时候重点关注于以下几个方面:

(1)是否支持Ajax请求(该类请求需要考虑每次键盘按下后触发重复加载的时间间隔);

(2)当数据库存在多条数据范围的时候,考虑最大显示个数(最好是由后端去控制最大显示个数);

(3)自定义下拉选项风格;

(4)未找到匹配文本时的提示信息;

(5)自定义格式的JSON数据结构转换;

带着上述的几点考虑,使用的Bootstrap3-typeahead版本的自动补全实现,GitHub项目地址为:https://github.com/bassjobsen/Bootstrap-3-Typeahead,整理出来的demo如下。

注意:

(1)html渲染方式的时候,data-source的属性值必须为标准JSON格式的对象数据,即该属性如果采用英文双引号包裹并且数组中的各项值为英文单引号包裹的时候会出现问题;

(2)默认情况下输入“j”提示有:java、javascript选项,选择java后,再清空文本框内的文本,再次输入“j”发现并未有提示,原因可能是由于本次跟上次输入的字母一致,导致未发起新的请求;

(3)一个复杂的满足日常需求的自动补全插件则包括了:支持匹配文本的字母大小写及高亮显示,并且支持未找到匹配项的提示与处理的Ajax请求数据的方式,同时对于点击未找到选项时的赋值与取值的特殊处理,见本文示例处的Ajax复杂应用;

示例运行


image.png


输入提示.gif

参考代码

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>bootstrap-typeahead</title>

<meta name="viewport" content="width=device-width, initial-scale=1" />

<link rel="shortcut icon" href="http://www.chendd.cn/app/images/favicon.ico" type="image/x-icon" />

<link href="../dialog/prism/prism.css" rel="stylesheet" />

<link href="../bootstrap.min.css" rel="stylesheet" />

</head>

<body>

<form class="form-horizontal" role="form">

    <div class="form-group">

        <label class="col-sm-2 control-label">html属性渲染字符串数组</label>

        <div class="col-sm-10">

            <input type="text" class="form-control" autocomplete="off" placeholder="请输入编程语言"

                   data-provide="typeahead"

                   data-source='["java" , "javascript" , "html" , "xml" , "css" , "sql" , "pascal" , "c#" , "c"]'

            />

        </div>

    </div>

    <div class="form-group">

        <label class="col-sm-2 control-label">html属性渲染对象数组</label>

        <div class="col-sm-10">

            <input type="text" class="form-control"

                   data-provide="typeahead" data-source='[{"id":"1" , "name":"java"},{"id":"2" , "name":"javascript"},

                   {"id":"3" , "name":"sql"},{"id":"4" , "name":"abcdefghijklmnopqrstuvwxyz"}]'

                   autocomplete="off" placeholder="请输入编程语言" />

        </div>

    </div>

    <div class="form-group">

        <label for="basic_text_id" class="col-sm-2 control-label">js渲染</label>

        <div class="col-sm-10">

            <input type="text" id="basic_text_id" class="form-control" autocomplete="off" placeholder="请输入编程语言" />

        </div>

    </div>

    <div class="form-group">

        <label for="basic_text_id" class="col-sm-2 control-label"><b>ajax复杂应用</b></label>

        <div class="col-sm-10">

            <input type="text" id="ajax_text_id" class="form-control" autocomplete="off" placeholder="请输入字母数字" />

            <input type="hidden" id="ajax_hidden_id" />

        </div>

    </div>

</form>

 

<hr/>

本页面源代码为:

<pre class="language-html line-numbers" data-src="index.html"></pre>

<hr/>

复杂示例数据源:

<pre  class="language-json line-numbers" data-src="example.json"></pre>

<hr/>

 

<script src="../jquery/jquery.min.js"></script>

<script src="../popper.min.js"></script>

<script src="../bootstrap.min.js"></script>

<script src="js/bootstrap3-typeahead.min.js"></script>

<script src="../dialog/prism/prism.js"></script>

<script type="text/javascript">

//运行js函数

function runCode(codeId){

    var code = document.getElementById(codeId).innerText;

    eval(code);

}

$(function(){

    $('#basic_text_id').typeahead({

        autoSelect: false,

        source: function(query, process) {

            return process(["java" , "javascript" , "html" , "xml" , "css" , "sql" , "pascal" , "c#" , "c"]);

        }

    });

    //ajax 方式的负责应用

    $('#ajax_text_id').typeahead({

        autoSelect: false,//自动选择

        items: 10,//下拉选项个数

        fitToElement: false,

        delay: 500,//延迟毫米

        //minLength: 0,//最小触发请求的文本长度

        //高亮格式化

        highlighter: function (item) {

            var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');

            return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {

                return '<strong style="color: red;">' + match + '</strong>'

            });

        },

        //选中项后触发

        afterSelect: function (item) {

            //选择项为未找到

            $('#ajax_text_id').val(item.text);

            //实际值

            $("#ajax_hidden_id").val(item.userName);

            if(item.text != ""){

                alert("选中项:名称=" + item.name + ",年龄=" + item.age + ",性别=" + item.sex);

            }

        },

        //发送ajax

        source: function (query , process) {

            $.ajax({

                url: "example.json",

                success: function (result) {

                    //----------------此部分代码不为实际代码

                    var exist = false;

                    for(var i=0 , lens = result.length ; i < lens ; i++) {

                        var value = result[i].userName.toLowerCase();

                        if(value.indexOf(query.toLowerCase()) != -1){

                            exist = true;

                            break;

                        }

                    }

                    //----------------此部分代码不为实际代码

                    if(result.length == 0 || exist == false){

                        return process([{"text" : "" , "name": "未找到包含 " + query + " 的数据"}]);

                    }

 

                    var list = result.map(function (item) {

                        var data = {"name": item.userName , "age": item.age , "sex": item.sex , "text" : item.userName};

                        return data;

                    });

                    return process(list);

                },

                error: function () {

                    return process([{"text" : "" , "name": "未找到包含 " + query + " 的数据"}]);

                }

            });

        }

    });

});

</script>

</body>

</html>

复杂示例数据源

[

  {"userName" : "12345" , "age" : 24 , "sex" : "女"},

  {"userName" : "1Aabcde" , "age" : 25 , "sex" : "女"},

  {"userName" : "1567890" , "age" : 26 , "sex" : "男"},

  {"userName" : "1BbjfWio" , "age" : 27 , "sex" : "女"},

  {"userName" : "1fdafsa" , "age" : 28 , "sex" : "女"},

  {"userName" : "1fasfdaFw" , "age" : 29 , "sex" : "男"},

  {"userName" : "1fdscJgr" , "age" : 30 , "sex" : "女"},

  {"userName" : "1u7543v" , "age" : 31 , "sex" : "男"},

  {"userName" : "1210388jf" , "age" : 32 , "sex" : "女"},

  {"userName" : "1vmdo9o4" , "age" : 33 , "sex" : "女"},

  {"userName" : "140ks23s" , "age" : 34 , "sex" : "男"},

  {"userName" : "1mskjFWW3" , "age" : 35 , "sex" : "女"},

  {"userName" : "143043ks" , "age" : 36 , "sex" : "女"},

  {"userName" : "1dsm9320djkw" , "age" : 37 , "sex" : "男"},

  {"userName" : "1dsklw9032" , "age" : 38 , "sex" : "女"}

]

参考代码

https://gitee.com/88911006/chendd-examples/tree/master/bootstrap


 点赞


 发表评论

当前回复:作者

 评论列表


留言区