在Enter上执行搜索?
我有此表格:
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>
当我点击输入(即#locations搜索)时,我想添加一个EventListener。 我尝试这样做:
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("search", () => {
console.log("search entered");
});
这是:
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
两者都不是控制台。
执行此操作的正确/更好方法是什么?
I have this form:
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>
I want to add an eventListener when I hit enter on the input(i.e. #locationsearch).
I tried doing this:
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("search", () => {
console.log("search entered");
});
and this:
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
Both are not console-logging.
What is the correct/better way to perform this action?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
OnSubmit事件将发生在表单本身上,而不是输入。因此,您可以使用表格上的ID代替将其直接定位为目标。
The onsubmit event would happen on the form itself, not the input. So you could use an id on the form instead to target it directly.
您可以处理输入元素的键盘事件处理程序。如果按下输入键,请检查键代码。
You could handle it keydown event handler of input element. And check the key code if Enter key pressed.
您可以为此使用 按键 事件。
You can use keypress event for this.