我循环浏览我的 Web 应用程序中的每个段落并搜索段落中的每个单词。大约有 2000 个段落可供搜索。任何改进此代码的建议将不胜感激。
function searchBarFunction(){
const wimesParagraph = document.querySelectorAll('.wimesParagraph');
let textToSearch = searchBar.value
textToSearch = textToSearch.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
let pattern = new RegExp(`${textToSearch}`,"gi");
filterOn = 0;
let textToSearch = searchBar.value
textToSearch = textToSearch.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
let pattern = new RegExp(`${textToSearch}`,"gi");
for(let i = 0; i < paragraph.children[0].children[4].children[0].childElementCount; i++){
paragraph.children[0].children[4].children[0].children[i].innerHTML = paragraph.children[0].children[4].children[0].children[i].textContent.replace(pattern, match => {
paragraph.style.display = 'flex';
x = 1;
if(searchBar.value === ""){
paragraph.dataset.searched = "not-searched";
} else{
paragraph.dataset.searched = "searched";
}
if(filterOn === 1){
if(paragraph.dataset.filter === "no-filters"){
paragraph.style.display = 'none';
}
}
return `<mark>${match}</mark>`;
})
}
})
}
我试图将段落放入数组中,然后搜索文本,然后更新 DOM 一次,因为我认为它会多次更新 DOM,这会导致延迟
İ 如果我是你,我的代码会像那样
function searchBarFunction() {
const paragraphs = document.getElementsByClassName('wimesParagraph');
const searchText = searchBar.value
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`${searchText}`, "gi");
for (let i = 0; i < paragraphs.length; i++) {
const paragraph = paragraphs[i];
const children = paragraph.children[0].children[4].children[0];
const hasMatch = searchForPatternInElement(pattern, children);
updateParagraphDisplay(paragraph, hasMatch);
if (filterOn === 1) {
filterParagraphIfNeeded(paragraph);
}
}
}
function searchForPatternInElement(pattern, element) {
let hasMatch = false;
for (let i = 0; i < element.childElementCount; i++) {
const child = element.children[i];
const originalText = child.textContent;
const markedText = originalText.replace(pattern, `<mark>${match}</mark>`);
hasMatch |= (markedText !== originalText);
child.innerHTML = markedText;
}
return hasMatch;
}
function updateParagraphDisplay(paragraph, hasMatch) {
paragraph.style.display = hasMatch ? 'flex' : 'none';
paragraph.dataset.searched = searchBar.value ? 'searched' : 'not-searched';
}
function filterParagraphIfNeeded(paragraph) {
if (paragraph.dataset.filter === 'no-filters') {
paragraph.style.display = 'none';
}
}