触发按钮单击Enter

时间:2018-07-23 10:30:13

标签: php jquery html

按此代码,如果我按Enter键,它将返回警报。但是我想编写一个可以按A键盘的代码,它将重定向到页面

<!DOCTYPE html>
<html>
<body>

<h3>Trigger Button Click on Enter</h3>
<p>Press the "Enter" key inside the input field to trigger the button.</p>

<input id="myInput" value="Some text..">
<button id="myBtn" onclick="javascript:alert('Hello World!')">Button</button>

<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("myBtn").click();
    }
});
</script>

</body>
</html>

如何自定义它。请帮助

2 个答案:

答案 0 :(得分:1)

这应该是您需要的一切:               

<h3>Trigger Button Click on Enter</h3>
<p>Press the "Enter" key inside the input field to trigger the button.</p>

<input id="myInput" value="Some text..">

<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
    event.preventDefault();
    // a key, remove if for every key 
    // or use this to find your wanted keycode http://keycode.info/
    if (event.keyCode === 65) { 

       location.href = "https://google.com";
    }
});
</script>

</body>
</html>

答案 1 :(得分:1)

使用65作为键“ A”

 <!DOCTYPE html>
    <html>
    <body>

    <h3>Trigger Button Click on Enter</h3>
    <p>Press the "Enter" key inside the input field to trigger the button.</p>

    <input id="myInput" value="Some text..">
    <button id="myBtn" onclick="javascript:alert('Hello World!')">Button</button>

    <script>
    var input = document.getElementById("myInput");
    input.addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode === 65) {
            //redirect to any page
        }
    });
    </script>

    </body>
    </html>