javascript实现html中关键字查询
时间: 2023-10-26 09:06:05 浏览: 93
可以使用 JavaScript 来实现在 HTML 中进行关键字查询。以下是一个实现的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Keyword Search</title>
</head>
<body>
<h1>Keyword Search</h1>
<label for="search-input">Enter keyword:</label>
<input type="text" id="search-input">
<button id="search-button">Search</button>
<p id="search-results"></p>
<script>
const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
const searchResults = document.getElementById('search-results');
function searchKeyword(keyword) {
// Get all the elements that can contain the keyword
const searchElements = document.querySelectorAll('p, h1, h2, h3, h4, h5, h6');
// Loop through the elements and search for the keyword
let resultCount = 0;
searchElements.forEach(element => {
if (element.textContent.includes(keyword)) {
// Highlight the keyword in the element
const highlightedText = element.textContent.replace(new RegExp(keyword, 'gi'), match => `<mark>${match}</mark>`);
element.innerHTML = highlightedText;
resultCount++;
}
});
// Display the number of search results
const resultText = resultCount > 0 ? `${resultCount} results found.` : 'No results found.';
searchResults.innerHTML = resultText;
}
searchButton.addEventListener('click', event => {
event.preventDefault();
const keyword = searchInput.value;
searchKeyword(keyword);
});
</script>
</body>
</html>
```
这段代码包含了一个输入框和一个按钮,当用户点击按钮时,脚本会搜索 HTML 页面中包含关键字的元素,并在文本中使用 `<mark>` 标签突出显示关键字。此外,还会在页面上显示搜索结果的数量。
阅读全文