html - 有没有办法让“输入”击键单击特定按钮?
问题描述
因此,我正在设置一个具有以下键和输入的虚拟键盘以及一个具有动态 onclick 功能的主按钮。我希望能够按下回车键并点击那个主按钮,但由于某种原因它不起作用。当我按下回车键时,它将单击我按下的最后一个按钮
我尝试使用此功能
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("MasterButton").click();
}
});
但它没有用。系统可以识别击键,但它也可能只是默认设置。
<div id="VirtualKey" style="float:left">
<input id="btn1" type="button" onclick="input(this);" class="keypad" value="1" />
<input id="btn2" type="button" onclick="input(this);" class="keypad" value="2" />
<input id="btn3" type="button" onclick="input(this);" class="keypad" value="3" />
<br />
<input id="btn4" type="button" onclick="input(this);" class="keypad" value="4" />
<input id="btn5" type="button" onclick="input(this);" class="keypad" value="5" />
<input id="btn6" type="button" onclick="input(this);" class="keypad" value="6" />
<br />
<input id="btn7" type="button" onclick="input(this);" class="keypad" value="7" />
<input id="btn8" type="button" onclick="input(this);" class="keypad" value="8" />
<input id="btn9" type="button" onclick="input(this);" class="keypad" value="9" />
<br />
<input id="btn0" type="button" onclick="input(this);" class="keypad" value="0" />
<input id="btn." type="button" onclick="input(this);" class="keypad" value="." />
<input id="btnDel" type="button" value="DEL" onclick="del();" class="keypad"></button>
</div>
<div id="Master Input Section"><br><input type="number" step="0.1" id="Student"></input>
<div id="Master Button Section"><br><button type="submit" id="MasterButton" class="button" onclick="">Master</button></div>
<script>
function input(e) {
// Get the TextBox object.
var tbInput = document.getElementById("Student");
// As e is the button, its value is the text on it.
// Add the value to the TextBox.
tbInput.value = tbInput.value + e.value;
}
function del() {
// Get the TextBox object.
var tbInput = document.getElementById("Student");
// Remove the last char in the TextBox.
tbInput.value = tbInput.value.substr(0, tbInput.value.length - 1);
}
</script>
预期结果,输入键将单击 MasterButton
更新发现错误码TypeError: input.addEventListener is not a function[了解更多]
解决方案
var ENTER_KEY = 13;
$(document).on('keypress', function(e) {
var code = e.keyCode || e.which
if (code == ENTER_KEY) {
$("#MasterButton").trigger("click");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
推荐阅读
- python - 当我尝试使用 Django 实现 Bootstrap 主题时,加载静态不起作用
- c# - 使用 C# 控制台应用程序执行脚本
- reactjs - 当我使用自定义反应钩子时,如何用多个不同的响应来模拟?
- windows - 正在生成格式错误的标头
- c# - 当光线投射没有击中任何东西时,“对象未设置为对象的实例”
- kubernetes - 掌舵升级后,Kubernetes 的秘密变得一团糟
- r - R 中的 API 错误 curl:收到致命的 SSL/TLS 警报(握手错误)
- javascript - 由于从输入触发的更改事件,复选框需要单击 2 次才能进行更改
- group-by - 发票表中枢轴的最大计数
- r - 在 r 中的许多列上应用一个函数