单击搜索按钮后开始搜索
单击搜索按钮时,我必须启动搜索。因此,我在搜索按钮上添加了单击事件。当我单击按钮时,启动搜索功能将被调用。该功能在输入元素上添加了一个事件。现在,假设我已经键入corm,然后单击搜索按钮,什么也不会发生。但是,如果我以后键入其他内容,则会激活其他搜索。如何正确执行?
document.querySelector('.searchBtn').addEventListener('click',
startSearch); //button
const inputSearch = document.querySelector('.inputSearch');
function startSearch(){
inputSearch.addEventListener('keyup', searchFunction);
}
I have to start the search when search button is clicked. So I have added click event on search button. When I click on button startSearch function is called. And that function adds an event on input element. Now let's say I have typed TEXT in form and I clicked the search button, nothing happens. But If I later type something else search is activated. How to do this properly?
document.querySelector('.searchBtn').addEventListener('click',
startSearch); //button
const inputSearch = document.querySelector('.inputSearch');
function startSearch(){
inputSearch.addEventListener('keyup', searchFunction);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
加载html文档后,您将必须立即设置事件侦听器(请参阅 domcontentloaded事件)。单击搜索按钮后,您将注册事件处理程序,但是在单击时需要启动搜索,因此您需要在此之前设置事件处理程序。然后在事件处理程序中激活搜索功能。仅当事件发生之前设置事件处理程序时,才可以注册事件。
一旦输入字段中的值更改或单击搜索按钮,以下实现将启动搜索。
You will have to set the event listeners as soon as the HTML document is loaded (See DOMContentLoaded event). You are registering the event handler once the search button is clicked, but you need to start the search when it is clicked so you need to set the event handler before that. Then activate the search function in the event handler. An event can only be registered if an event handler is set before the event occurs.
The following implementation will start a search once the value in the input field changes or the search button is clicked.