[英]Trigger a button click with JavaScript when Enter key is pressed
I want to trigger a button click when the Enter button is pressed in my page.我想在页面中按下 Enter 按钮时触发按钮单击。 I know how to do it if it's in a form.
如果它是一种形式,我知道该怎么做。 Like this
像这样
<form>
<input id="myInput" placeholder="Some text.." value="">
<input type="submit" id="myBtn" value="Submit">
</form>
<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
</script>
But how to trigger the button even when the Enter is pressed irrespective of where the focus is in the input element or not.但是,即使按下 Enter 键,也不管焦点在输入元素中的哪个位置,如何触发按钮。 just pressing the Enter button will trigger the button in the page.
只需按 Enter 按钮就会触发页面中的按钮。 How can I do that?
我怎样才能做到这一点?
You just need to add your event listener to the document instead of the input您只需要将事件侦听器添加到文档而不是输入
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
You can use document
您可以使用
document
When use input.addEventListener
then it will listen event from input only and when use document.addEventListener
then it will listen from the entire page当使用
input.addEventListener
它只会从 input 中监听事件,当使用document.addEventListener
它会从整个页面监听
var input = document.getElementById("myInput"); document.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); document.getElementById("myBtn").click(); } });
<form> <input id="myInput" placeholder="Some text.." value=""> <input type="submit" id="myBtn" value="Submit"> </form>
you can bind the keyup event on window or document您可以在窗口或文档上绑定 keyup 事件
window.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
console.log("oops!")
}
});
不是将事件监听器绑定到那个输入元素,而是像这个 document.addEventListener("keyup", your_function_here); 那样全局绑定监听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.