我有這個表格:
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>
我想在輸入時添加一個事件監聽器(即#locationsearch)。我試過這樣做:
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("search", () => {
console.log("search entered");
});
還有這個:
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
兩者都不是控制臺日志記錄。
執行此操作的正確/更好的方法是什么?
uj5u.com熱心網友回復:
onsubmit 事件將發生在表單本身上,而不是輸入上。因此,您可以在表單上使用 id 來直接定位它。
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
<form id="locationsearch">
<label for="locationsearch">Location:</label>
<input type="search" name="locationsearch" />
</form>
uj5u.com熱心網友回復:
您可以處理輸入元素的 keydown 事件處理程式。如果按下 Enter 鍵,則檢查密鑰代碼。
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("keydown", (e) => {
if (e.code === 'Enter') {
// Do Something ? Search
}
});
uj5u.com熱心網友回復:
您可以為此使用按鍵事件。
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("keypress", () => {
if (event.key === "Enter") {
event.preventDefault();
let inputVal = document.getElementById("locationsearch").value;
console.log("search entered " inputVal);
document.getElementById("locationsearch").value = "";
}
});
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475602.html
標籤:javascript dom 添加事件监听器
下一篇:設定html后添加事件的正確方法