BootStrap Typeahead自动补全插件实例代码


Posted in Javascript onAugust 10, 2016

关键代码如下所示:

$('#Sale').typeahead({
ajax: {
url: '@Url.Action("../Contract/GetSale")',
//timeout: 300,
method: 'post',
triggerLength: 1,
loadingClass: null,
preProcess: function (result) {
return result;
}
},
display: "Value",
val: "ID",
items: 10,
itemSelected: function (item, val, text) {
$("#SalesID").val(val);
}
});

这种 typeahead自动补全不是bootstrap常用的typeahead.js。 以下是typeahead.js代码(如果有bootstrap3-typeahead.js更好)

// ----------------------------------------------------------------------------
//
// bootstrap-typeahead.js 
//
// Twitter Bootstrap Typeahead Plugin
// v1.2.2
// https://github.com/tcrosen/twitter-bootstrap-typeahead
//
//
// Author
// ----------
// Terry Rosen
// tcrosen@gmail.com | @rerrify | github.com/tcrosen/
//
//
// Description
// ----------
// Custom implementation of Twitter's Bootstrap Typeahead Plugin
// http://twitter.github.com/bootstrap/javascript.html#typeahead
//
//
// Requirements
// ----------
// jQuery 1.7+
// Twitter Bootstrap 2.0+
//
// ----------------------------------------------------------------------------
!
function ($) {
"use strict";
//------------------------------------------------------------------
//
// Constructor
//
var Typeahead = function (element, options) {
this.$element = $(element);
this.options = $.extend(true, {}, $.fn.typeahead.defaults, options);
this.$menu = $(this.options.menu).appendTo('body');
this.shown = false;
// Method overrides 
this.eventSupported = this.options.eventSupported || this.eventSupported;
this.grepper = this.options.grepper || this.grepper;
this.highlighter = this.options.highlighter || this.highlighter;
this.lookup = this.options.lookup || this.lookup;
this.matcher = this.options.matcher || this.matcher;
this.render = this.options.render || this.render;
this.select = this.options.select || this.select;
this.sorter = this.options.sorter || this.sorter;
this.source = this.options.source || this.source;
if (!this.source.length) {
var ajax = this.options.ajax;
if (typeof ajax === 'string') {
this.ajax = $.extend({}, $.fn.typeahead.defaults.ajax, { url: ajax });
} else {
this.ajax = $.extend({}, $.fn.typeahead.defaults.ajax, ajax);
}
if (!this.ajax.url) {
this.ajax = null;
}
}
this.listen();
}
Typeahead.prototype = {
constructor: Typeahead,
//=============================================================================================================
//
// Utils
//
//=============================================================================================================
//------------------------------------------------------------------
//
// Check if an event is supported by the browser eg. 'keypress'
// * This was included to handle the "exhaustive deprecation" of jQuery.browser in jQuery 1.8
//
eventSupported: function (eventName) {
var isSupported = (eventName in this.$element);
if (!isSupported) {
this.$element.setAttribute(eventName, 'return;');
isSupported = typeof this.$element[eventName] === 'function';
}
return isSupported;
},
//=============================================================================================================
//
// AJAX
//
//=============================================================================================================
//------------------------------------------------------------------
//
// Handle AJAX source 
//
ajaxer: function () {
var that = this,
query = that.$element.val();
if (query === that.query) {
return that;
}
// Query changed
that.query = query;
// Cancel last timer if set
if (that.ajax.timerId) {
clearTimeout(that.ajax.timerId);
that.ajax.timerId = null;
}
if (!query || query.length < that.ajax.triggerLength) {
// Cancel the ajax callback if in progress
if (that.ajax.xhr) {
that.ajax.xhr.abort();
that.ajax.xhr = null;
that.ajaxToggleLoadClass(false);
}
return that.shown ? that.hide() : that;
}
// Query is good to send, set a timer
that.ajax.timerId = setTimeout(function () {
$.proxy(that.ajaxExecute(query), that)
}, that.ajax.timeout);
return that;
},
//------------------------------------------------------------------
//
// Execute an AJAX request
//
ajaxExecute: function (query) {
this.ajaxToggleLoadClass(true);
// Cancel last call if already in progress
if (this.ajax.xhr) this.ajax.xhr.abort();
var params = this.ajax.preDispatch ? this.ajax.preDispatch(query) : { query: query };
var jAjax = (this.ajax.method === "post") ? $.post : $.get;
this.ajax.xhr = jAjax(this.ajax.url, params, $.proxy(this.ajaxLookup, this));
this.ajax.timerId = null;
},
//------------------------------------------------------------------
//
// Perform a lookup in the AJAX results
//
ajaxLookup: function (data) {
var items;
this.ajaxToggleLoadClass(false);
if (!this.ajax.xhr) return;
if (this.ajax.preProcess) {
data = this.ajax.preProcess(data);
}
// Save for selection retreival
this.ajax.data = data;
items = this.grepper(this.ajax.data);
if (!items || !items.length) {
return this.shown ? this.hide() : this;
}
this.ajax.xhr = null;
return this.render(items.slice(0, this.options.items)).show();
},
//------------------------------------------------------------------
//
// Toggle the loading class
//
ajaxToggleLoadClass: function (enable) {
if (!this.ajax.loadingClass) return;
this.$element.toggleClass(this.ajax.loadingClass, enable);
},
//=============================================================================================================
//
// Data manipulation
//
//=============================================================================================================
//------------------------------------------------------------------
//
// Search source
//
lookup: function (event) {
var that = this,
items;
if (that.ajax) {
that.ajaxer();
}
else {
that.query = that.$element.val();
if (!that.query) {
return that.shown ? that.hide() : that;
}
items = that.grepper(that.source);
if (!items || !items.length) {
return that.shown ? that.hide() : that;
}
return that.render(items.slice(0, that.options.items)).show();
}
},
//------------------------------------------------------------------
//
// Filters relevent results 
//
grepper: function (data) {
var that = this,
items;
if (data && data.length && !data[0].hasOwnProperty(that.options.display)) {
return null;
}
items = $.grep(data, function (item) {
return that.matcher(item[that.options.display], item);
});
return this.sorter(items);
},
//------------------------------------------------------------------
//
// Looks for a match in the source
//
matcher: function (item) {
return ~item.toLowerCase().indexOf(this.query.toLowerCase());
},
//------------------------------------------------------------------
//
// Sorts the results
//
sorter: function (items) {
var that = this,
beginswith = [],
caseSensitive = [],
caseInsensitive = [],
item;
while (item = items.shift()) {
if (!item[that.options.display].toLowerCase().indexOf(this.query.toLowerCase())) {
beginswith.push(item);
}
else if (~item[that.options.display].indexOf(this.query)) {
caseSensitive.push(item);
}
else {
caseInsensitive.push(item);
}
}
return beginswith.concat(caseSensitive, caseInsensitive);
},
//=============================================================================================================
//
// DOM manipulation
//
//=============================================================================================================
//------------------------------------------------------------------
//
// Shows the results list
//
show: function () {
var pos = $.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
});
this.$menu.css({
top: pos.top + pos.height,
left: pos.left
});
this.$menu.show();
this.shown = true;
return this;
},
//------------------------------------------------------------------
//
// Hides the results list
//
hide: function () {
this.$menu.hide();
this.shown = false;
return this;
},
//------------------------------------------------------------------
//
// Highlights the match(es) within the results
//
highlighter: function (item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
});
},
//------------------------------------------------------------------
//
// Renders the results list
//
render: function (items) {
var that = this;
items = $(items).map(function (i, item) {
i = $(that.options.item).attr('data-value', item[that.options.val]);
i.find('a').html(that.highlighter(item[that.options.display], item));
return i[0];
});
items.first().addClass('active');
this.$menu.html(items);
return this;
},
//------------------------------------------------------------------
//
// Item is selected
//
select: function () {
var $selectedItem = this.$menu.find('.active');
this.$element.val($selectedItem.text()).change();
this.options.itemSelected($selectedItem, $selectedItem.attr('data-value'), $selectedItem.text());
return this.hide();
},
//------------------------------------------------------------------
//
// Selects the next result
//
next: function (event) {
var active = this.$menu.find('.active').removeClass('active');
var next = active.next();
if (!next.length) {
next = $(this.$menu.find('li')[0]);
}
next.addClass('active');
},
//------------------------------------------------------------------
//
// Selects the previous result
//
prev: function (event) {
var active = this.$menu.find('.active').removeClass('active');
var prev = active.prev();
if (!prev.length) {
prev = this.$menu.find('li').last();
}
prev.addClass('active');
},
//=============================================================================================================
//
// Events
//
//=============================================================================================================
//------------------------------------------------------------------
//
// Listens for user events
//
listen: function () {
this.$element.on('blur', $.proxy(this.blur, this))
.on('keyup', $.proxy(this.keyup, this));
if (this.eventSupported('keydown')) {
this.$element.on('keydown', $.proxy(this.keypress, this));
} else {
this.$element.on('keypress', $.proxy(this.keypress, this));
}
this.$menu.on('click', $.proxy(this.click, this))
.on('mouseenter', 'li', $.proxy(this.mouseenter, this));
},
//------------------------------------------------------------------
//
// Handles a key being raised up
//
keyup: function (e) {
e.stopPropagation();
e.preventDefault();
switch (e.keyCode) {
case 40:
// down arrow
case 38:
// up arrow
break;
case 9:
// tab
case 13:
// enter
if (!this.shown) {
return;
}
this.select();
break;
case 27:
// escape
this.hide();
break;
default:
this.lookup();
}
},
//------------------------------------------------------------------
//
// Handles a key being pressed
//
keypress: function (e) {
e.stopPropagation();
if (!this.shown) {
return;
}
switch (e.keyCode) {
case 9:
// tab
case 13:
// enter
case 27:
// escape
e.preventDefault();
break;
case 38:
// up arrow
e.preventDefault();
this.prev();
break;
case 40:
// down arrow
e.preventDefault();
this.next();
break;
}
},
//------------------------------------------------------------------
//
// Handles cursor exiting the textbox
//
blur: function (e) {
var that = this;
e.stopPropagation();
e.preventDefault();
setTimeout(function () {
if (!that.$menu.is(':focus')) {
that.hide();
}
}, 150)
},
//------------------------------------------------------------------
//
// Handles clicking on the results list
//
click: function (e) {
e.stopPropagation();
e.preventDefault();
this.select();
},
//------------------------------------------------------------------
//
// Handles the mouse entering the results list
//
mouseenter: function (e) {
this.$menu.find('.active').removeClass('active');
$(e.currentTarget).addClass('active');
}
}
//------------------------------------------------------------------
//
// Plugin definition
//
$.fn.typeahead = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('typeahead'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('typeahead', (data = new Typeahead(this, options)));
}
if (typeof option === 'string') {
data[option]();
}
});
}
//------------------------------------------------------------------
//
// Defaults
//
$.fn.typeahead.defaults = {
source: [],
items: 8,
menu: '<ul class="typeahead dropdown-menu"></ul>',
item: '<li><a href="#"></a></li>',
display: 'name',
val: 'id',
itemSelected: function () { },
ajax: {
url: null,
timeout: 300,
method: 'post',
triggerLength: 3,
loadingClass: null,
displayField: null,
preDispatch: null,
preProcess: null
}
}
$.fn.typeahead.Constructor = Typeahead;
//------------------------------------------------------------------
//
// DOM-ready call for the Data API (no-JS implementation)
// 
// Note: As of Bootstrap v2.0 this feature may be disabled using $('body').off('.data-api') 
// More info here: https://github.com/twitter/bootstrap/tree/master/js
//
$(function () {
$('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
var $this = $(this);
if ($this.data('typeahead')) {
return;
}
e.preventDefault();
$this.typeahead($this.data());
})
});
}(window.jQuery);

以上所述是小编给大家介绍的BootStrap Typeahead自动补全插件实例代码 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
为调试JavaScript添加输出窗口的代码
Feb 07 Javascript
jQuery EasyUI API 中文文档 - ComboTree组合树
Oct 11 Javascript
javascript中为某个元素指定事件的三种方式
Aug 07 Javascript
JS+HTML5实现的前端购物车功能插件实例【附demo源码下载】
Oct 17 Javascript
SVG动画vivus.js库使用小结(实例代码)
Sep 14 Javascript
javaScript之split与join的区别(详解)
Nov 08 Javascript
原生JS实现的双色球功能示例
Feb 02 Javascript
vue配置多页面的实现方法
May 22 Javascript
vue-router 源码之实现一个简单的 vue-router
Jul 02 Javascript
Angular动态绑定样式及改变UI框架样式的方法小结
Sep 03 Javascript
JS实现获取当前所在周的周六、周日示例分析
May 11 Javascript
Layui数据表格之单元格编辑方式
Oct 26 Javascript
BootStrap中Datepicker控件带中文的js文件
Aug 10 #Javascript
JS获取鼠标选中的文字
Aug 10 #Javascript
浅析JavaScript函数的调用模式
Aug 10 #Javascript
JavaScript实现刷新不重记的倒计时
Aug 10 #Javascript
JavaScript中自带的 reduce()方法使用示例详解
Aug 10 #Javascript
JS控制静态页面之间传递参数获取参数并应用的简单实例
Aug 10 #Javascript
浅谈JS中的bind方法与函数柯里化
Aug 10 #Javascript
You might like
php数组函数序列之array_combine() - 数组合并函数使用说明
2011/10/29 PHP
PHP常用编译参数中文说明
2014/09/27 PHP
php根据用户名和手机号查询是否存在手机号码
2017/02/16 PHP
JavaScript asp.net 获取当前超链接中的文本
2009/04/14 Javascript
两个Javascript小tip资料
2010/11/23 Javascript
jquery入门——事件机制之事件中的冒泡现象示例解释
2020/09/12 Javascript
当滚动条滚动到页面底部自动加载增加内容的js代码
2014/05/13 Javascript
Javascript中call与apply的学习笔记
2014/09/22 Javascript
javascript 中__proto__和prototype详解
2014/11/25 Javascript
js实现格式化金额,字符,时间的方法
2015/02/26 Javascript
JavaScritp添加url参数并将参数加入到url中及更改url参数的方法
2015/10/26 Javascript
JS实现单击输入框弹出选择框效果完整实例
2015/12/14 Javascript
HTML5 实现的一个俄罗斯方块实例代码
2016/09/19 Javascript
深入理解Angularjs向指令传递数据双向绑定机制
2016/12/31 Javascript
基于Bootstrap表单验证功能
2017/11/17 Javascript
nodejs+mongodb aggregate级联查询操作示例
2018/03/17 NodeJs
Vue二次封装axios为插件使用详解
2018/05/21 Javascript
vue.js将时间戳转化为日期格式的实现代码
2018/06/05 Javascript
深入浅析Vue全局组件与局部组件的区别
2018/06/15 Javascript
快速解决bootstrap下拉菜单无法隐藏的问题
2018/08/10 Javascript
layui-tree实现Ajax异步请求后动态添加节点的方法
2019/09/23 Javascript
仿照Element-ui实现一个简易的$message方法
2020/09/14 Javascript
[06:59]DOTA2-DPC中国联赛3月7日Recap集锦
2021/03/11 DOTA
Python闭包执行时值的传递方式实例分析
2018/06/04 Python
influx+grafana自定义python采集数据和一些坑的总结
2018/09/17 Python
Django 视图层(view)的使用
2018/11/09 Python
pycham查看程序执行的时间方法
2018/11/29 Python
详解html5 canvas常用api总结(二)--绘图API
2016/12/14 HTML / CSS
MYPROTEIN澳大利亚官方网站:欧洲运动营养品牌
2019/06/26 全球购物
C++的几个面试题附答案
2016/08/03 面试题
什么是反射
2012/03/17 面试题
运动会报道稿300字
2014/10/02 职场文书
工作会议简报
2015/07/20 职场文书
CSS实现漂亮的时钟动画效果的实例代码
2021/03/30 HTML / CSS
Oracle表空间与权限的深入讲解
2021/11/17 Oracle
html用代码制作虚线框怎么做? dw制作虚线圆圈的技巧
2022/12/24 HTML / CSS