Hier ist der relevante Code:
Code: Select all
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.");
}
}
}
Code: Select all
Next
Previous
Love never dies. Love never dies. Love never dies.
Problem
Bei der Suche Wenn der Begriff das erste Wort im Textbereich ist (z. B. „Love“) und ich auf die Schaltfläche „Zurück“ klicke, wird nicht zum letzten Vorkommen zurückgesprungen. Wenn ich jedoch nach einem Begriff wie „nie“ suche, funktioniert es einwandfrei und führt wie erwartet eine Schleife aus.
Erwartetes Verhalten
- < li>Wenn die Schaltfläche „Weiter“ gedrückt wird, wird das nächste Vorkommen gesucht.
- Wenn die Schaltfläche „Vorherige“ gedrückt wird, wird eine Schleife zum letzten Vorkommen ausgeführt, wenn die erste Übereinstimmung erreicht wird.