2015-09-04 125 views
0

我正在使用jqueryUI自動完成腳本。問題是我想限制它提供給6的建議的數量,因爲它提供了太多的建議。這是腳本:jqueryui自動完成的建議數量

$.get('file.txt', function(x) { 

    var i; 
    var pos = 0; 
    var availableTags = []; 

    x = x.split(/[\#\n]+/); 

    for (i = 0; i < x.length; i = i + 4) 
     availableTags[pos++] = x[i]; 

    console.log(availableTags); 

    $(function() { 
     $("#search").autocomplete({source: availableTags}); 
     response(availableTags.slice(0, 6)); 
    }); 

    }, 'text'); 

我發現和excellent solution by Andrew Whitaker,但不能使它的工作。他建議使用

response(availableTags.slice(0, 6)); 

任何解決方案來限制我的腳本上的建議數量?

回答

1

你可以覆蓋_renderMenu功能,顯示最大的N個項目

$.ui.autocomplete.prototype._renderMenu = function(ul, items) { 
    var self = this; 
    $.each(items, function(index, item) { 
     if (index < 10) // here we define how many results to show 
     {self._renderItem(ul, item);} 
     }); 
} 

或切片迴應:

$("#search").autocomplete({ 
    source: function(request, response) { 
     var results = $.ui.autocomplete.filter(availableTags, request.term); 

     response(results.slice(0, 6)); 
    } 
}); 
+0

非常感謝michal pavlik,作品幾乎完美,但影響到html結果和CSS。你介意我是否等待更簡單的答案? – Kathlyn

+0

當然,我編輯了我的文章,並添加了切片結果的更簡單的解決方案。 –

+0

那麼,第二個是行不通的:'(但這可能是我的錯,我在我的問題中編輯了代碼,以向您展示我是如何包含您的代碼的,您是否發現任何錯誤? – Kathlyn

0
$(function() { 
    var limit = 3; 
    var tags = [ 
     "hello","hi", "him", 'here',"his", "honour", "banquet" 
    ]; 
    $("#search").autocomplete({ 
     source: tags.slice(0, limit), 

     }); 
}); 

請找到上述解決方案,讓我知道它是否適合你。