Monthly Archives: 八月 2012

Hello World 美图酷图

让bootstrap的自动补齐功能支持ajax数据源


如上图,bootstrap的自动补齐功能非常好用($(‘#xxx’).typeahead()),可以自定义筛选、排序方法,对键盘操作的支持也非常好,可惜,美中不足的是。。。它不支持可变数据源,如果提示数据需要通过ajax取得的,就用不了了
无奈,只能改它源码了~~~只要简单的3个小修改

1. 添加updateSource方法

//在Typeahead类的构造方法里,添加:
this.updateSource = this.options.updateSource || false

2. 鼠标输入时,先执行updateSource方法

//找到keyup方法,修改switch的default项:
if(this.updateSource){
  var that = this
  this.updateSource(this.$element.val(), function(source){
    //取得新数据源后的回调
    that.source = source;
    that.lookup()
  });
}else{
  //如果没有配置updateSource,直接执行lookup方法
  this.lookup()
}

3. 修改筛选数据源的方法

//找到lookup方法,然后同时是否配置了updateSource,判断是否执行默认的筛选方法
if(!this.updateSource){
  items = $.grep(this.source, function (item) {
    if (that.matcher(item)) return item
  })
  items = this.sorter(items)
}else{
  items = this.source;
}

ok,大功告成
并且,这里只是“扩展了typeahead方法”,如果使用固定的数据源,还可以照着之前的方式使用,在需要使用ajax数据源的时候:

	$('#input_typeahead').typeahead({
		source : [],
		items : 7,
		highlighter : function(item){
			return item;
		},
		updateSource : function(inputVal, callback){
			$.ajax({
				type : 'POST',
				url : '/test/ajax_search_tip',
				dataType : 'json',//返回需要展示的json数组
				data : {length : 5, input : inputVal},
				success : function(d){
					callback(d);
				}
			});
		}
	});

——-
嘿嘿,顺便发个美图