html实现js查找
HTML 实现 JavaScript 查找功能
在 HTML 中实现 JavaScript 查找功能通常涉及监听用户输入、遍历 DOM 元素并匹配内容。以下是实现方法:
监听输入框事件
创建输入框并监听 keyup 或 input 事件,触发查找逻辑:
<input type="text" id="searchInput" placeholder="输入关键词">
<div id="content">
<p>这是第一段文本</p>
<p>这是第二段文本</p>
</div>
JavaScript 查找逻辑 遍历目标元素,检查内容是否匹配关键词:
document.getElementById('searchInput').addEventListener('input', function() {
const keyword = this.value.toLowerCase();
const elements = document.querySelectorAll('#content p');
elements.forEach(element => {
const text = element.textContent.toLowerCase();
if (text.includes(keyword)) {
element.style.backgroundColor = 'yellow';
} else {
element.style.backgroundColor = '';
}
});
});
高亮匹配文本的进阶实现
若需高亮显示匹配的具体文本而非整段,可使用正则表达式替换:
function highlightText(element, keyword) {
const regex = new RegExp(keyword, 'gi');
const html = element.innerHTML.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
);
element.innerHTML = html;
}
// 在事件监听中调用
elements.forEach(element => {
highlightText(element, keyword);
});
动态加载内容的查找
对于动态生成的内容(如 AJAX 加载),需在数据渲染后绑定查找逻辑:
fetch('data.json').then(response => response.json()).then(data => {
const container = document.getElementById('content');
container.innerHTML = data.map(item => `<p>${item.text}</p>`).join('');
// 重新绑定查找事件
bindSearch();
});
function bindSearch() {
document.getElementById('searchInput').addEventListener('input', function() {
// 查找逻辑同上
});
}
性能优化建议
对于大量数据,考虑以下优化:
- 使用
debounce函数减少频繁触发(如 Lodash 的_.debounce) - 限制搜索范围,避免全 DOM 遍历
- 对静态数据预建搜索索引
// 示例:debounce 实现
function debounce(func, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), delay);
};
}
document.getElementById('searchInput').addEventListener(
'input',
debounce(function() { /* 查找逻辑 */ }, 300)
);






