Вот соответствующий код:
Код: Выделить всё
let currentMatchIndex = -1; // Tracks the current match index
function resetIndex() {
currentMatchIndex = -1;
}
function highlightMatch(startIndex, endIndex) {
const textarea = document.getElementById('myTextarea');
textarea.setSelectionRange(startIndex, endIndex);
textarea.focus();
}
function next() {
const findTerm = document.getElementById('findInput').value;
const textarea = document.getElementById('myTextarea');
const text = textarea.value;
if (findTerm) {
const startIndex = text.indexOf(findTerm, currentMatchIndex + 1);
if (startIndex !== -1) {
currentMatchIndex = startIndex;
} else {
currentMatchIndex = text.indexOf(findTerm); // Loop back to first occurrence
}
if (currentMatchIndex !== -1) {
highlightMatch(currentMatchIndex, currentMatchIndex + findTerm.length);
} else {
alert("Find term not found.");
}
}
}
function previous() {
const findTerm = document.getElementById('findInput').value;
const textarea = document.getElementById('myTextarea');
const text = textarea.value;
if (findTerm) {
const startIndex = text.lastIndexOf(findTerm, currentMatchIndex - 1);
if (startIndex !== -1) {
currentMatchIndex = startIndex;
} else {
currentMatchIndex = text.lastIndexOf(findTerm); // Loop to last occurrence
}
if (currentMatchIndex !== -1) {
highlightMatch(currentMatchIndex, currentMatchIndex + findTerm.length);
} else {
alert("Find term not found.");
}
}
}Код: Выделить всё
Next
Previous
Love never dies. Love never dies. Love never dies.Проблема
При поиске термин — это первое слово в текстовой области (например, «Любовь»), и я нажимаю кнопку «Предыдущий», он не возвращается к последнему вхождению. Однако если я ввожу такой термин, как «никогда», он работает нормально и зацикливается, как и ожидалось.
Ожидаемое поведение
- < li>При нажатии кнопки «Далее» выполняется поиск следующего вхождения.
- При нажатии кнопки «Предыдущий» происходит переход к последнему вхождению при достижении первого совпадения.
Подробнее здесь: https://stackoverflow.com/questions/793 ... st-word-in
Мобильная версия