2012-04-11 16 views

回答

1

不,你不能沒有一些額外的魔法。幸運的是,這個魔法非常簡單而有趣。我真的很喜歡解決這個難題:)

請考慮這個example我創建了。

$.fn.typeahead.Constructor.prototype.select = function() { 
    var val = this.$menu.find('.active').attr('data-value'), 
     newVal = this.$element.val().replace(/@.*$/, '@' + val); 
    this.$element.val(newVal); 
    this.$element.change(); 
    return this.hide(); 
}; 

$('#email').typeahead({ 
    source: ['gmail', 'hotmail', 'yahoo'], 
    matcher: function(item) { 
     var m = this.query.indexOf('@'), 
      search; 

     if (!~m) { 
      return false; 
     } 

     search = this.query.substr(m + 1).toLowerCase(); 
     return search.length && ~item.toLowerCase().indexOf(search); 
    } 
}); 

首先,您需要定義您的自定義matcher函數,以便定義哪些值被認爲是合適的。這很容易。複雜的部分是您需要更改Typeahead原型,以便使插件能夠設置正確的輸入字段的新值:例如不是gmail,'雅虎',但像[email protected]等完整的電子郵件地址等。

+0

不錯;)感謝您的代碼。有什麼方法可以在下拉菜單中顯示完整的電子郵件([email protected],[email protected])? (所以用戶不會對選擇的值(gmail.com,mail.com)將替換他輸入的內容(tomas)感到困惑嗎? – 2012-04-12 13:20:01

+0

在這個世界上一切皆有可能!http://jsfiddle.net/hyxMh/7/ – dfsq 2012-04-12 13:53:27

+0

或者甚至更好:http://jsfiddle.net/hyxMh/8/ – dfsq 2012-04-12 13:55:35

0

其實我們不需要做一些擴展,只需使用像這樣的ajax函數。

$('.typeahead').typeahead({ 
    source: function (typeahead, query) { 

    var con = $('#input1').val(); 
    var atpos = con.indexOf('@'); 
    if(atpos==-1){ 
     return [con+'@gmail.com',con+'@sina.com',con+'@qq.com',con+'@126.com']; 
    }else if(atpos>0){ 
     //get value before @ 
     var tmp = con.substr(0,atpos); 
     return [tmp+'@gmail.com',tmp+'@sina.com',tmp+'@qq.com',tmp+'@126.com']; 
    }else{ 

    } 
    //return ['alpha','beta','bravo','delta','epsilon','gamma','zulu']; 
    } 
}); 
相關問題