搜索按钮的JavaScript代码通常涉及到监听按钮的点击事件,并在事件触发时执行搜索操作。以下是一个简单的示例,展示了如何编写这样的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Button Example</title>
</head>
<body>
<input type="text" id="searchInput" placeholder="Enter search term...">
<button id="searchButton">Search</button>
<script src="script.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', function() {
const searchButton = document.getElementById('searchButton');
const searchInput = document.getElementById('searchInput');
searchButton.addEventListener('click', function() {
const searchTerm = searchInput.value;
performSearch(searchTerm);
});
function performSearch(term) {
// 这里可以添加实际的搜索逻辑
console.log('Searching for:', term);
// 例如,可以使用AJAX请求将搜索词发送到服务器
// fetch('/search', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({ term: term })
// })
// .then(response => response.json())
// .then(data => {
// console.log('Search results:', data);
// })
// .catch(error => {
// console.error('Error:', error);
// });
}
});
addEventListener
方法监听特定事件(如点击事件)。通过以上步骤和示例代码,你可以实现一个基本的搜索按钮功能,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云