2014-09-30 4 views
1

Я установил плагин типа twart, но я не могу получить ограничение на работу.Предел Typeahead Twitter не работает

enter image description here Я поместил его в двух различных положениях:

$('input.typeahead').typeahead({ 
limit: 5, 
hint: true, 
highlight: false, 
minLength: 1 
}, { 
name: 'country', 
displayKey: 'value', 
source: substringMatcher(countries) 

И я также попытался это:

$('input.typeahead').typeahead({ 

hint: true, 
highlight: false, 
minLength: 1 
}, { 
limit: 5, 
name: 'country', 
displayKey: 'value', 
source: substringMatcher(countries) 

Остальная часть моего кода:

var substringMatcher = function (strs) { 
return function findMatches(q, cb) { 
    var matches, substringRegex; 

    // an array that will be populated with substring matches 
    matches = []; 

    // regex used to determine if a string contains the substring `q` 
    substrRegex = new RegExp(q, 'i'); 

    // iterate through the pool of strings and for any string that 
    // contains the substring `q`, add it to the `matches` array 
    $.each(strs, function (i, str) { 
     if (substrRegex.test(str)) { 
      // the typeahead jQuery plugin expects suggestions to a 
      // JavaScript object, refer to typeahead docs for more info 
      matches.push({ 
       value: str 
      }); 
     } 
    }); 

    cb(matches); 
}; 
}; 

var countries = [ "United States", "United Kingdom", "Canada", "Andorra", "United Arab Emirates", "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", "Angola", "Antarctica", "Argentina", "American Samoa", "Austria", "Australia", "Aruba", "Åland", "Azerbaijan", "Bosnia and Herzegovina", "Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", "Burundi", "Benin", "Saint Barthélemy", "Bermuda", "Brunei", "Bolivia", "Bonaire", "Brazil", "Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", "Cocos [Keeling] Islands", "Congo", "Central African Republic", "Republic of the Congo", "Switzerland", "Ivory Coast", "Cook Islands", "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape Verde", "Curacao", "Christmas Island", "Cyprus", "Czechia", "Germany", "Djibouti", "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", "Falkland Islands", "Micronesia", "Faroe Islands", "France", "Gabon", "Grenada", "Georgia", "French Guiana", "Guernsey", "Ghana", "Gibraltar", "Greenland", "Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia and the South Sandwich Islands", "Guatemala", "Guam", "Guinea-Bissau", "Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras", "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "Isle of Man", "India", "British Indian Ocean Territory", "Iraq", "Iran", "Iceland", "Italy", "Jersey", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", "Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "North Korea", "South Korea", "Kuwait", "Cayman Islands", "Kazakhstan", "Laos", "Lebanon", "Saint Lucia", "Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg", "Latvia", "Libya", "Morocco", "Monaco", "Moldova", "Montenegro", "Saint Martin", "Madagascar", "Marshall Islands", "Macedonia", "Mali", "Myanmar [Burma]", "Mongolia", "Macao", "Northern Mariana Islands", "Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", "Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", "Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway", "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint Pierre and Miquelon", "Pitcairn Islands", "Puerto Rico", "Palestine", "Portugal", "Palau", "Paraguay", "Qatar", "Réunion", "Romania", "Serbia", "Russia", "Rwanda", "Saudi Arabia", "Solomon Islands", "Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia", "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", "Somalia", "Suriname", "South Sudan", "São Tomé and Príncipe", "El Salvador", "Sint Maarten", "Syria", "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern Territories", "Togo", "Thailand", "Tajikistan", "Tokelau", "East Timor", "Turkmenistan", "Tunisia", "Tonga", "Turkey", "Trinidad and Tobago", "Tuvalu", "Taiwan", "Tanzania", "Ukraine", "Uganda", "U.S. Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vatican City", "Saint Vincent and the Grenadines", "Venezuela", "British Virgin Islands", "U.S. Virgin Islands", "Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Kosovo", "Yemen", "Mayotte", "South Africa", "Zambia", "Zimbabwe"]; 

$('input.typeahead').typeahead({ 
limit: 5, 
hint: true, 
highlight: false, 
minLength: 1 
}, { 
name: 'country', 
displayKey: 'value', 
source: substringMatcher(countries) 

}); 
$('.typeahead.input-sm').siblings('input.tt-hint').addClass('hint-small'); 
$('.typeahead.input-lg').siblings('input.tt-hint').addClass('hint-large'); 

CSS:

<div class="row form-row m-l-20 m-r-20 xs-m-l-10 xs-m-r-10"> 
    <div class="col-md-6 col-sm-6"> 
     <input name="country" type="text" class="typeahead input-sm form-control" autocomplete="off" spellcheck="false" placeholder="Country"> 
    </div> 
</div> 

ответ

3

Я считаю, что вы можете столкнуться с проблемой, когда опция limit была перемещена с typeahead.js на двигатель предложения typeahead.js Bloodhound.

От Bloodhound docs;

limit - Максимальное количество предложений для возврата от Bloodhound#get. Если не достигнуто, источник данных попытается выполнить повторную загрузку предложений с remote. По умолчанию 5.

Альтернативой может быть настройка minLength (минимальная длина символа, необходимая до того, как рекомендации начнут получать визуализацию) до более высокого номера, чем значение по умолчанию 1.

1

Я узнал, что опция limit-head имеет ошибочное поведение.

В соответствии с рекомендациями в этом thread подумать об использовании этой вилки вместо: https://github.com/corejavascript/typeahead.js

Я мог бы спасти часы отладки, если бы я использовал один перед

0

я провел целый день, прежде чем я нашел решение.

И, наконец, установив предел после того, как «проблема» решила проблему в моем случае.

Так попробуйте следующее:

$('input.typeahead').typeahead({ 
    hint: true, 
    highlight: false, 
    minLength: 1 
    }, 
    { 
    name: 'country', 
    displayKey: 'value', 
    source: substringMatcher(countries), 
    limit: Number.MAX_VALUE 
}); 
Смежные вопросы