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

关键代码如下所示:

$('#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自动补全插件实例代码 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • 使用Bootstrap typeahead插件实现搜索框自动补全的方法

    这就是贴代码的坏处之一:搜索框快被网友玩儿坏了!!!有故意输入空格的,有输入or 1=1的,有alert的,有html乱入的.......而且好像还在玩儿,随他们去吧,只要开心就好. 在项目中,经常会用到输入框的自动补全功能,就像百度.淘宝等搜索框一样:当用户输入首字母.关键词时,后台会迅速将与此相关的条目返回并显示到前台,以便用户选择,提升用户体验.当然本项目的补全功能和这些大厂的技术是没有可比性的,但用于站内搜索也是绰绰有余了. 接触到的自动补全插件主要有两个:autocomplete和ty

  • Bootstrap学习系列之使用 Bootstrap Typeahead 组件实现百度下拉效果

    UnderScore官网:http://underscorejs.org/ 参考文档:http://www.css88.com/doc/underscore/ 页面代码: @{ ViewBag.Title = "Index"; } <script src="Scripts/bootstrap-typeahead.js"></script> <script src="Scripts/underscore-min.js"

  • Bootstrap3使用typeahead插件实现自动补全功能

    很酷的一个自动补全插件 http://twitter.github.io/typeahead.js 在bootstrap中使用typeahead插件,完成自动补全 相关的文档:https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md 数据源: Local:数组 prefectch:json remote等方式 -----------------------------------------------

  • 使用bootstrap typeahead插件实现输入框自动补全之问题及解决办法

    根据网上查找到的 typeahead使用方法,到最后一步时就出错,数据能从数据库读取出来,但在输入框显示提示时,全都显为:underfined.捉摸了半天都发现不了问题出在哪儿.后来在http://blog.64cm.com/post/2014/08/13/%E4%BD%BF%E7%94%A8bootstrap-typeahead%E6%8F%92%E4%BB%B6 上不经意发现这么一句话:"在当前版本的typeahead中,已经不再支持在source属性中直接调用ajax方法获取数据源了.&q

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

    关键代码如下所示: $('#Sale').typeahead({ ajax: { url: '@Url.Action("../Contract/GetSale")', //timeout: 300, method: 'post', triggerLength: 1, loadingClass: null, preProcess: function (result) { return result; } }, display: "Value", val: "

  • JSP + ajax实现输入框自动补全功能 实例代码

    下面是我用ajax实现的输入框自动补全功能,数据库数据很少,大体模仿出了百度首页的提示功能,当然,人家百度的东西不只是这么简单的!先看运行效果: index.jsp(包含主要的js代码) 复制代码 代码如下: <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath();

  • Visual Studio Code上添加小程序自动补全插件的操作方法

    Visual Studio Code(简称"VS Code" )是Microsoft在2015年4月30日Build开发者大会上正式宣布一个运行于 Mac OS X.Windows和 Linux 之上的,针对于编写现代Web和云应用的跨平台源代码编辑器, 可在桌面上运行,并且可用于Windows,macOS和Linux.它具有对JavaScript,TypeScript和Node.js的内置支持,并具有丰富的其他语言(例如C++,C#,Java,Python,PHP,Go)和运行时(例

  • vim自动补全插件YouCompleteMe(YCM)安装过程解析

    Vim是全平台上一个高度可拓展的编辑器.它本身只是一个简陋的编辑器,但是因为有各种插件而变得强大.使用Vim编写代码就不免遇到代码补全的问题.常用的代码补全插件有两个:日本人shougo写的neocomplete和前Google工程师Valloric写的YouCompleteMe.用的人比较多的还是YouCompleteMe.YouCompleteMe被称为Vim最难配置的插件,当初配置好YouCompleteMe也是费了九牛二虎之力,印象中是花了整整一个晚上.回报也是显然的,支持定义跳转,变量

  • php使HTML标签自动补全闭合函数代码

    简单解释一些代码: 第一个 ~(<[^>]+?>)~si 这个正则是匹配<--->中的内容.简单说是所有的<标签>. 第二个 ~<([a-z0-9]+)[^/>]*?/>~si 这个正则是匹配<--/>中的内容.是单闭合标签 如<br /> 第三个 ~</([a-z0-9]+)[^/>]*?>~si 这个正则是匹配</......>中的内容.也就是结束标签 如</a> 第四个 ~&

  • Nginx的伪静态配置中使用rewrite来实现自动补全的实例

    nginx+php 使用的时候经常需要伪静态,一般大家都手动设置.那有没有办法让 nginx 自动补全路径呢? 这两天折腾很久,才实现了这样一个功能: 请求 /a/b/c 若文件不存在,查找 /a/b/index.php,/c 作为 PATH_INFO: 若文件不存在,查找 /a/index.php,/b/c 作为 PATH_INFO: 若文件不存在,查找 /index.php,/a/b/c 作为 PATH_INFO: 若文件不存在,返回 404. 虽然这种损耗性能的行为不适合部署,但在本机调试

  • inputSuggest文本框输入时提示、自动完成效果(邮箱输入自动补全插件)

    像QQ邮箱提示.百度的搜索框提示.淘宝的商品搜索提示等,现在有不少的网站都有类似效果,以提升用户体验. 使用方法: new InputSuggest({ input HTMLInputElement 必选 data Array ['sina.cn','sina.com','2008.sina.com','vip.sina.com.cn'] 必选 containerCls 容器className itemCls 容器子项className activeCls 高亮子项className width

  • Python 自动补全(vim)

    一.vim python自动补全插件:pydiction 可以实现下面python代码的自动补全: 1.简单python关键词补全 2.python 函数补全带括号 3.python 模块补全 4.python 模块内函数,变量补全 5.from module import sub-module 补全 想为vim启动自动补全需要下载插件,地址如下: http://vim.sourceforge.net/scripts/script.php?script_id=850 https://github

随机推荐