javascript - 如何检测javascript中的任何kepress
问题描述
当用户在输入字段上时,我有以下代码检测任何按键:
// Trigger clicking the submit button if the user ever presses enter
$('.Textinput').on('keypress', function(e) {
if(e.which == 13){//Enter key pressed
$('#payment-form').click();
}
});
但是,如果页面上有按键,无论光标/活动元素在哪里,我将如何做同样的事情?
解决方案
使用文档,在以下示例中,它从整个文档中捕获反映到计数器的按键事件。这个解决方案在 chrome 中对我有用。
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
i = 0;
$(document).ready(function() {
$(document).keypress(function() {
$("span").text(i += 1);
});
});
</script>
</head>
<body>
Type anything on page or Enter your name:
<input type="text">
<p>
Keypresses: <span>0</span>
</p>
</body>
</html>
推荐阅读
- django - 使用 Django 频道定期向所有人广播消息
- javascript - 使用 jQuery 为 c# 构建视图模型
- google-sheets - 将逗号分隔的谷歌表单答案转换为电子表格中的多行
- php - Laravel:500 服务器错误但没有错误日志?
- mapping - 将 IoT 中心引入 ADX 时映射自定义属性
- javascript - 如何在角度反应形式控件中添加小数,其值从 1 或更大开始
- reactjs - Fetch().then() 不返回数据
- javascript - react-native 中的动画展开/折叠文本包装器
- google-api - Youtube 请求无法完成,因为您已超出配额
- javascript - 获取数组的前 3 个元素,然后是另一个 3 个元素,然后是 javascript 中的另一个 3 个元素