简体   繁体   English

按下Enter键时触发HTML按钮

[英]trigger a HTML button when you press Enter

I am trying to make a button key "trigger" on a specific page using tampermonkey. 我试图使用tampermonkey在特定页面上使按钮键“触发”。 Instead of using mouse click every time to click Button called "continue". 而不是每次都使用鼠标单击来单击称为“继续”的按钮。

So when I click keyboard button "ENTER" this hover button should be automatically clicked, theres any ready to use code while I can just put this HTML code. 因此,当我单击键盘按钮“ ENTER”时,应自动单击此悬停按钮,在我可以放置此HTML代码的同时,有任何准备使用的代码。 Thanks. 谢谢。

<button id="simplicityPayment-START" type="submit" autocomplete="off" class="nf-btn nf-btn-primary nf-btn-solid nf-btn-oversize" data-uia="action-submit-payment">START MEMBERSHIP</button>

USING JQUERY 使用JQUERY

You can use easy jQuery to achieve it. 您可以使用简单的jQuery实现它。
Just add a cdn given below in your main HTML page 只需在您的HTML主页面中添加下面给出的CDN

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

And just open a script tags and copy paste this code. 然后只需打开脚本标签并复制粘贴此代码即可。

$(document).keypress(function(event){

var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
    $("#simplicityPayment-START").click();
}});


USING PURE JAVASCRIPT (NO EXTERNAL LIBRARY) 使用纯JAVASCRIPT(无外部库)

EDIT 1: As don't own the website & using tampermonkey. 编辑1:由于不拥有该网站并使用tampermonkey。 Okay so there is another way to achieve this, that is Pure JAVASCRIPT. 好的,还有另一种方法可以实现,那就是Pure JAVASCRIPT。 it requires no CDN. 它不需要CDN。 just Add this JAVASCRIPT. 只需添加此JAVASCRIPT。

window.addEventListener('keyup', function (e) {
  if (e.keyCode === 13) {
     var button = document.getElementById("simplicityPayment-START");
     button.click();
  }
}, false);

You can add autofocus attribute to button, but I'm not sure if this will work with tampermonkey. 您可以将autofocus属性添加到按钮,但是我不确定这是否可以与tampermonkey一起使用。 Because I think it need to be in html when page load. 因为我认为页面加载时必须在html中。

You can also use this: 您还可以使用以下命令:

 document.querySelector('[type="submit"]').focus();

it will give focus to button and you will be able to submit the form with space or enter. 它将重点放在按钮上,您将能够提交带有空格的表格或输入。 But this if you click outside of the button you will not be able to press enter to submit the form. 但是,如果您在按钮之外单击,将无法按Enter提交表单。 If you need to do some action then you can add this focus after user do something. 如果您需要执行某些操作,则可以在用户执行某项操作后添加此焦点。 You can also add focus when you click on document. 您也可以在单击文档时添加焦点。

var button = document.querySelector('[type="submit"]');
window.addEventListener('click', function() {
   button.focus();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM