bootstrap 自动补全插件Bootstrap Typeahead 组件

使用 Bootstrap Typeahead 组件

Bootstrap 中的 Typeahead 组件就是通常所说的自动完成 AutoComplete,功能很强大,但是,使用上并不太方便。这里我们将介绍一下这个组件的使用。

image

第一,简单使用

首先,最简单的使用方式,就是直接在标记中声明,通过 data-provide="typeahead" 来声明这是一个 typeahead 组件,通过** data-source=** 来提供数据。当然了,你还必须提供 bootstrap-typeahead.js 脚本。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><html>
<head>
<link href="bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>

<div style="margin: 50px 50px">
<label for="product_search">Product Search: </label>
<input id="product_search" type="text" data-provide="typeahead" data-source='["Deluxe Bicycle", "Super Deluxe Trampoline", "Super Duper Scooter"]'>
</div>

<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/bootstrap-typeahead.js"></script>

</body>
</html></pre>

[
复制代码

](javascript:void(0); "复制代码")

第二,使用脚本填充数据

通常,我们使用脚本来填充数据,那么,页面可以变成如下的形式。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><html>
<head>
<link href="bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>

<div style="margin: 50px 50px">
<label for="product_search">Product Search: </label>
<input id="product_search" type="text" data-provide="typeahead">
</div>

<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/bootstrap-typeahead.js"></script>

<script> (document).ready(function() { // Workaround for bug in mouse item selection
$.fn.typeahead.Constructor.prototype.blur = function() { var that = this;
setTimeout(function () { that.hide() }, 250);
};

$('#product_search').typeahead({
source: function(query, process) { return ["Deluxe Bicycle", "Super Deluxe Trampoline", "Super Duper Scooter"];
}
});
}) </script>

</body>
</html></pre>

[
复制代码

](javascript:void(0); "复制代码")

注意,我们提供了一个 source 函数来提供数据,这个函数接收两个参数,第一个参数 query 表示用户的输入,第二个参数是 process 函数,这个 process 函数是 typeahead 提供的,用来处理我们的数据。

如果你希望通过 Ajax 调用从服务器端获取匹配的数据,那么,在异步完成的处理函数中,你需要获取一个匹配的字符串数组,然后,将这个数组作为参数,调用 process 函数。

第三,支持 Ajax 获取数据

说了半天,数据都是从本地获取的,到底如何从服务器端获取数据呢?

其实很简单,在 source 函数中,自己调用 Ajax 方法来获取数据,主要注意的是,在获取数据之后,调用 typeahead 的 process 函数处理即可。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">('#product_search').typeahead({ source: function (query, process) { var parameter = {query: query};.post('@Url.Action("AjaxService")', parameter, function (data) {
process(data);
});
}
});</pre>

[
复制代码

](javascript:void(0); "复制代码")

当然了,在服务器上,你需要创建一个服务来提供数据,这里,我们演示使用随机数来生成一组随机数据的方法。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">public ActionResult AjaxService(string query)
{
System.Collections.ArrayList list = new System.Collections.ArrayList();
System.Random random = new Random(); for (int i = 0; i < 20; i++)
{ string item = string.Format("{0}{1}", query, random.Next(10000));
list.Add(item);
} return this.Json(list);
}</pre>

[
复制代码

](javascript:void(0); "复制代码")

第四,使用 highlighter 和 updater

除了使用 source 函数之外,还可以使用 highlighter 函数来特别处理匹配项目的显示,使用 updater 函数,在选择了某个匹配项之后,做出一些后继的处理。

image

默认的 highlighter 是这样实现的,item 是匹配的项目,找到匹配的部分之后,使用 <strong> 加粗了。

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">highlighter: function (item) {
var query = this.query.replace(/[-[]{}()*+?.,\^|#\s]/g, '\\><') return item.replace(new RegExp('(' + query + ')', 'ig'), function (1, match) {
return '<strong>' + match + '</strong>'
})
}</pre>

而 updater 的默认实现就更加简单了。

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">updater: function (item) {
return item
}</pre>

我们可以重写这两个函数,来实现自定义的处理。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><html>
<head>
<link href="bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>

<div style="margin: 50px 50px">
<label for="product_search">Product Search: </label>
<input id="product_search" type="text" data-provide="typeahead">
</div>

<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/bootstrap-typeahead.js"></script>

<script> (document).ready(function() { // Workaround for bug in mouse item selection
$.fn.typeahead.Constructor.prototype.blur = function() { var that = this;
setTimeout(function () { that.hide() }, 250);
};

$('#product_search').typeahead({
source: function(query, process) { return ["Deluxe Bicycle", "Super Deluxe Trampoline", "Super Duper Scooter"];
},

  highlighter: function(item) { return "==>" + item + "<==";
  },

  updater: function(item) {
     console.log("'" + item + "' selected."); return item;

}
});
}) </script>
</body>
</html></pre>

[
复制代码

](javascript:void(0); "复制代码")

第五,使用对象数据

实际上,你的数据可能是一组对象而不是一个字符串数组,下面的例子中,我们使用一个产品对象的数组来说明,每个产品对象有一个 id 编号,还有名称 name 和价格 price .

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><html>
<head>
<link href="~/Content/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>

<div style="margin: 50px 50px">
    <label for="product_search">Product Search: </label>
    <input id="product_search" type="text" data-provide="typeahead">
</div>
<script src="~/Content/dist/js/jquery.js"></script>
<script src="~/Content/dist/js/bootstrap-typeahead.js"></script>
<script src="~/Content/dist/js/underscore-min.js"></script>

<script> $(document).ready(function ($) { // Workaround for bug in mouse item selection

$.fn.typeahead.Constructor.prototype.blur = function () { var that = this;
setTimeout(function () { that.hide() }, 250);
}; var products = [
{
id: 0,
name: "Deluxe Bicycle",
price: 499.98 },
{
id: 1,
name: "Super Deluxe Trampoline",
price: 134.99 },
{
id: 2,
name: "Super Duper Scooter",
price: 49.95 }
];

        $('#product_search').typeahead({
            source: function (query, process) { var results = _.map(products, function (product) { return product.name;
                });
                process(results);
            },

            highlighter: function (item) { return "==>" + item + "<==";
            },

            updater: function (item) {
                console.log("'" + item + "' selected."); return item;
            }
        });
    }) </script>

</body>
</html></pre>

[
复制代码

](javascript:void(0); "复制代码")

第六,高级用法

我们希望能够在提示中显示产品的更加详细的信息。

首先,修改我们的 source 函数,原来这个函数返回一个字符串的数组,现在我们返回一个产品 id 的数组,但是,process 函数期望得到一个字符串数组的参数,所以,我们将每个 id 都转换为字符串类型。

然后,typeahead 组件就会调用 matcher 函数来检查用户的输入是否与某个项目匹配,你可以使用产品的 id 在产品列表中获取产品对象,然后检查产品的名称与用户的输入是否匹配。

默认的 matcher 直接使用用户的输入来匹配,我们如果使用 id 的话,显然不能匹配,我们需要重写 matcher 函数。

matcher 接收一个当前项目的字符串,用户当前的输入为 this.query,匹配返回 true, 否则返回 false. 默认的 matcher 如下:

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">, matcher: function (item) { return ~item.toLowerCase().indexOf(this.query.toLowerCase())
}</pre>

将它重写为永远匹配,直接返回 true。而在 highlighter 中将显示结果替换为希望的产品名称和价格组合。在下一步的 highlighter 中,我们使用 Underscore 组件中的 find 方法,通过产品的 id 在产品列表中获取产品对象,然后,显示产品名称和价格的组合。

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">highlighter: function (id) { var product = _.find(products, function (p) { return p.id == id;
}); return product.name + " ($" + product.price + ")";
}</pre>

默认的 updater 直接返回当前匹配的内容,我们这里是一个 id, 需要重写。

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">updater: function (item) { return item
}</pre>

在用户选择之后,typeahead 将会调用 updater 函数,我们通过产品的 id 在产品列表中获取产品对象,然后

最后,updater 函数返回一个产品名称的字符串,为输入框提供内容。setSelectedProduct 是我们的一个自定义函数。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">updater: function (id) { var product = _.find(products, function (p) { return p.id == id;
});
that.setSelectedProduct(product); return product.name;
}</pre>

[
复制代码

](javascript:void(0); "复制代码")

下面是全部的代码。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><html>
<head>
<link href="~/Content/dist/css/bootstrap.min.css" rel="stylesheet" />

</head>
<body>

<div style="margin: 50px 50px">
    <label for="product_search">Product Search: </label>
    <input id="product_search" type="text" data-provide="typeahead">
    <div id="product" style="border-width: 1; padding: 5px; border-style: solid"></div>
</div>

<script src="~/Content/dist/js/jquery.js"></script>
<script src="~/Content/dist/js/bootstrap-typeahead.js"></script>
<script src="~/Content/dist/js/underscore-min.js"></script>

<script> $(document).ready(function ($) { // Workaround for bug in mouse item selection

$.fn.typeahead.Constructor.prototype.blur = function () { var that = this;
setTimeout(function () { that.hide() }, 250);
}; var products = [
{
id: 0,
name: "Deluxe Bicycle",
price: 499.98 },
{
id: 1,
name: "Super Deluxe Trampoline",
price: 134.99 },
{
id: 2,
name: "Super Duper Scooter",
price: 49.95 }
]; var that = this;

        $('#product_search').typeahead({
            source: function (query, process) {
                $('#product').hide(); var results = _.map(products, function (product) { return product.id + "";
                });
                process(results);
            },

            matcher: function (item) { return true;
            },

            highlighter: function (id) { var product = _.find(products, function (p) { return p.id == id;
                }); return product.name + " ($" + product.price + ")";
            },

            updater: function (id) { var product = _.find(products, function (p) { return p.id == id;
                });
                that.setSelectedProduct(product); return product.name;
            }

        });

        $('#product').hide(); this.setSelectedProduct = function (product) {
            $('#product').html("Purchase: <strong>" + product.name + " ($" + product.price + ")</strong>").show();
        }
    }) </script>

</body>
</html></pre>

[
复制代码

](javascript:void(0); "复制代码")

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容