[英]Can I add event to the button on click of input type=search?
是否有任何可用於單擊清除按鈕的事件僅出現在 html5 搜索輸入元素上?
這是我的嘗試。 但是,如果我使用“搜索”,則按 Enter 也會觸發該事件。
即,如果我按 Enter,控制台會清楚地打印出搜索
mySearchBar.addEventListener("keydown", (e) => {
if (e.keyCode === ENTER_KEY_CODE) {
console.log("search");
//Display search results
}
});
mySearchBar.addEventListener("search", () => {
console.log("clear");
// Click the cross button of input type=search to Clear the search results and display all
});
};
您可以使用eventListener 'input'
來檢查每次向輸入追加內容時輸入是否為空,如果沒有值則表示搜索輸入已被清除。
編輯:在 keydown 事件中進行增值測試
mySearchBar = document.getElementById('search'); mySearchBar.addEventListener("keydown", (e) => { if (e.key === 'Enter') { if (!e.currentTarget.value) console.log('cleared'); else console.log("search"); } }); mySearchBar.addEventListener('input', (e) => { if (!e.currentTarget.value) console.log('cleared'); })
<input type=search id=search>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.