柚子鬼博客官方

自动补全、自动提示的两种实现方式(前端实现与后端实现)

作者:柚子鬼博客官方 发布时间: 2020-11-18      32 人阅读    本文共计3773个字,预计阅读时长13分钟。

input输入框有时需要实现自动提示的功能,如下图:

那么怎么实现呢?一是使用autocomplete属性,二是直接调用后端的服务。下面分别记录一下代码,以供参考。

1.autocomplete

引入jquery-ui.min.css与jquery-ui.min.js,代码如下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="http://apps.bdimg.com/libs/jqueryui/1.10.4/css/jquery-ui.min.css">
    <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="http://apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
</head>
<body>
<input id="roadline">
</body>
<script type="text/javascript">
    $(function() {
        var availableTags = ["标缝路","诚信路","公诚路","万诚路","何寇路","何潘路","何新路","栎西路","房西路","文化东路","桃源东路","石家东路"];
        $( "#roadline" ).autocomplete({
            source:
                    function(request, response) {
                        var results = $.ui.autocomplete.filter(availableTags, request.term);
                        response(results.slice(0, 10));//只显示自动提示的前十条数据
                    },
            messages: {
                noResults: '',
                results: function() {}
            },
        });
 
    });
</script>
</html>
运行结果如下: 

2.直接调用后端服务

这种方法比较适合数据量大的情况,代码来自于同组师兄~~
代码如下(注意修改服务地址):

①index.html:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="aboveTool.css">
    <script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
</head>
 
<body>
    <div class="nav">
        <input type="text" id="txtAddress">
        <button class="search"></button>
    </div>
    <div>
        <div class="autoComplete">
            <ul></ul>
        </div>
    </div>
    <script>
    var autoBox = $(".autoComplete"),
        autoUl = $(".autoComplete ul"),
        textFill = $("#txtAddress");
        $("#txtAddress").on("keyup",function(e){
            //38:向上箭头;40:向下箭头;13:Enter键
            if(e.keyCode!=38&&e.keyCode!=40&&e.keyCode!=13){
                textSearch = $(this).val();
                setTimeout(function(){
                    autoMapPg.getData(textSearch);
                },100)
            }
        });
 
        $(".autoComplete ul").on("click",".suggestItem",function(e){
            var ft = $(this).attr("data-item");
            textFill.val(ft);
            autoMapPg.getData(ft).then(function (data) {
                //autoMapPg.abovePoint(data,ft)
            })
        });
 
        $(".search").on("click", function(e){
            var result = "",
                addressDistrict = "";
            if(!textFill.val()) return;
            autoMapPg.detailData(textFill.val()).then(function(data){
                //autoMapPg.abovePoint(data);
            })
        });
 
        var autoMapPg={
            //获取实时提示数据
            getData : function(textSearch){
                var dfd = $.Deferred(),
                    searchHtml = "",
                    addressDistrict = "";
                if(textSearch){
                    var ft = textSearch.toString().toLowerCase();
                    $.ajax({
                        type:"post",
                        data:ft,
                        url:"后端服务地址1",
                        success:function(result){
                            var result = JSON.parse(result);
                            console.log(result)
                            if(result.length){
                                for(var i=0,len=result.length;i<len;i++){                              
                                    searchHtml += '<li class="suggestItem" data-item="'+result[i].Name+'"><i class="default">'+result[i].Name+'</i></li>';
                                }
                            }
                            autoBox.show().siblings().hide();
                            autoUl.html(searchHtml);
                            listLength = autoUl.children().length;
                            dfd.resolve(result)
                        }
                    })
                    return dfd.promise();
                }else{
                    autoUl.html("");
                    $(".dataUpload").show();
                }
 
            },
            detailData : function(text){
                var dfd = $.Deferred();
                $.ajax({
                    type:"post",
                    url:"后端服务地址2",
                    data:"text="+text,
                    success:function(result){
                        var result = JSON.parse(result);
                        if(result.status == 0){
                            result = result.obj.results;
                            dfd.resolve(result)
                        }else{
                            console.log(result)
                        }
                    }
                })
                return dfd.promise()
            }
        };
    </script>
</body>
 
</html>

②aboveTool.css:

*{
  border: none;
  outline: none;
  padding: 0;
  margin: 0;
}
.nav .search {
        width: 44px;
        height: 28px;
        vertical-align: middle;
        background: url(search.png) no-repeat center;
        cursor: pointer; }
 
.nav {
      background: #fff;
      padding: 5px 0;
      margin-bottom: 5px; }
.nav input {
  height: 28px;
  margin-left: 20px;
  font-size: 16px;
  width: 80%;
  border-right: 1px solid #ccc;
  vertical-align: middle; }
.autoComplete {
    display: none;
    background: #fff;
    max-height: 350px;
    overflow: hidden;
    box-shadow: 1px 2px 1px rgba(0, 0, 0, 0.15); }
.autoComplete .suggestItem {
      height: 35px;
      line-height: 35px;
      cursor: pointer; }
      .autoComplete .suggestItem:hover {
        background: #e6e6e6; }
      .autoComplete .suggestItem i {
        padding-left: 39px;
        font-style: normal;
        color: #666;
        position: relative;
        z-index: 1;
        padding-top: 1px;
        background: url(autoText.png) no-repeat 12px; }
      .autoComplete .suggestItem em {
        margin-left: 10px;
        margin-right: 20px;
        font-style: normal;
        color: #999; }
    .autoComplete .suggestItem.hover {
      background: #e6e6e6; }
css中两张图片:
与 
运行结果:
柚子鬼博客拥有超强能力,极致后台体验,无插件,集成会员系统
柚子鬼博客 » 自动补全、自动提示的两种实现方式(前端实现与后端实现)

1 评论

  1. 博客真不错

发表评论

一个IT技术分享型博客

立即查看 了解详情