Я создал функцию «нравится/не нравится» для своего приложения Django.
Он использует jQuery/ajax и работает нормально, но нарушает мой поиск автозаполнения Devbridge (https://github.com/devbridge/jQuery-Автозаполнение).
Я решил заменить автозаполнение Devbridge автозаполнением vanilla JS отсюда: https://www.w3schools.com/howto/howto_js_autocomplete.asp.
Проблема в том, что в моем массиве более 10 000 элементов, поэтому, когда вы вводите первые несколько букв, он дает сотни или тысячи совпадений.
Я хотел бы ограничить количество совпадений. Любая помощь очень ценится. Я включил то, что, как я предполагаю, является наиболее подходящим кодом. Для полного кода просто проверьте ссылку.
<script>
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
Не совсем. Этот вопрос сложный. Ответить на него сможет только настоящий знаток Javascript. Как я уже сказал, в моем посте для расшифровки всего блока кода вам, вероятно, придется посетить исходную страницу.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


The problem is I have over 10,000 items in my array, so when you type in the first few letters it produces 100s or thousands of matches... I'd like to limit the number of matches.
Итак, давайте выясним, где он перебирает элементы в массиве, и добавим верхний предел количества элементов, которые можно добавить в список.
// This is where it loops all the items in the array
for (i = 0; i < arr.length; i++) {
...
// This is the logic which will dictate if an item is added to the list
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
...
}
}
Давайте добавим ограничение на количество совпадений, которые можно добавить в список, выйдя из цикла после достижения верхней границы.
let maxMatches = 10;
let matches = 0;
// Stop this loop once maximum matches have been found
for (i = 0; i < arr.length; i++) {
...
// This is the logic which will dictate if an item is added to the list
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
// Another match has been found, increment counter
matches = matches + 1;
...
}
// Break the loop if we hit max number of matches
if (matches >= maxMatches) {
break;
}
}
Надеюсь это поможет!
Решил проблему. Потрясающий. Спасибо!
Не могли бы вы добавить больше минимального и конкретного кода и сделать его более читабельным, пожалуйста?