- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
有没有办法在按下和释放键时运行 JavaScript 函数?
例如,我将如何运行函数 example()
当按下 T 键时?我以前见过这样的例子,但它们又长又乱,我无法让它们发挥作用。像这样的东西会放在 <script>
中吗?在<head>
?
最佳答案
要捕获整个页面,如页面帮助功能(也许您想捕获 F1?),那么您可以将脚本 block 放在 <head>
中标记,在脚本中。但是如果你想捕获一个DOM元素,那么你必须在DOM元素出现之后执行代码(因为脚本是按找到的方式解释的,如果DOM元素不存在,选择器引擎找不到它. 如果这没有意义,请说些什么,并且会找到一篇文章)。
但这里有一点供您考虑:当今优秀的 javascript 程序员导师建议在页面末尾加载所有 javascript。您可能唯一想在文档头部加载的是像 jQuery 这样的库,因为它们被广泛缓存,特别是如果您使用的是 jQuery 的 CDN 版本,因为它通常不会影响加载时间。
这样就回答了“我把代码块放在哪里,在 <head>
中?”的问题:没有。在最后。
现在,关于如何实际捕获击键,让我们分三部分来完成:
<html>
<head>
<title>blah blah</title>
<meta "woot, yay StackOverflow!">
</head>
<body>
<h1>all the headers</h1>
<div>all the divs</div>
<footer>All the ... ... footers?</footer>
<script>
/* the last example replaces this one */
function keyListener(event){
//whatever we want to do goes in this block
event = event || window.event; //capture the event, and ensure we have an event
var key = event.key || event.which || event.keyCode; //find the key that was pressed
//MDN is better at this: https://developer.mozilla.org/en-US/docs/DOM/event.which
if(key===84){ //this is for 'T'
doThing();
}
}
/* the last example replace this one */
var el = window; //we identify the element we want to target a listener on
//remember IE can't capture on the window before IE9 on keypress.
var eventName = 'keypress'; //know which one you want, this page helps you figure that out: http://www.quirksmode.org/dom/events/keys.html
//and here's another good reference page: http://unixpapa.com/js/key.html
//because you are looking to capture for things that produce a character
//you want the keypress event.
//we are looking to bind for IE or non-IE,
//so we have to test if .addEventListener is supported,
//and if not, assume we are on IE.
//If neither exists, you're screwed, but we didn't cover that in the else case.
if (el.addEventListener) {
el.addEventListener('click', keyListener, false);
} else if (el.attachEvent) {
el.attachEvent('on'+eventName, keyListener);
}
//and at this point you're done with registering the function, happy monitoring
</script>
</body>
</html>
这一行:var el = window; //we identify the element we want to target a listener on
也可能是 var el = document.getElementByTagName('input');
或其他一些文档选择器。该示例仍然以同样的方式工作。
var KeypressFunctions = [];
KeypressFunctions['T'.charCodeAt(0)] = function _keypressT() {
//do something specific for T
}
KeypressFunctions['t'.charCodeAt(0)] = function _keypresst() {
//do something specific for t
}
//you get the idea here
function keyListener(event){
//whatever we want to do goes in this block
event = event || window.event; //capture the event, and ensure we have an event
var key = event.key || event.which || event.keyCode; //find the key that was pressed
//MDN is better at this: https://developer.mozilla.org/en-US/docs/DOM/event.which
KeypressFunctions[key].call(); //if there's a defined function, run it, otherwise don't
//I also used .call() so you could supply some parameters if you wanted, or bind it to a specific element, but that's up to you.
}
这一切有什么用?
KeypressFunctions
是一个数组,我们可以用各种值填充它,但要让它们在某种程度上是人类可读的。数组中的每个索引都完成为 'T'.charCodeAt(0)
它给出了我们要为其添加函数的数组中索引位置的字符代码(event.which || event.keyCode
看起来很熟悉?)。所以在这种情况下,我们的数组只有两个定义的索引值,84
(T) 和 116
(吨)。我们可以把它写成 KeypressFunctions[84] = function ...
但这以人类可读时间更长为代价,人类可读性较差。始终先为自己编写代码,机器通常比您认为的更聪明。不要试图用逻辑来打败它,但如果你可以稍微优雅一点,也不要编写过多的 if-else block 。
啊!我忘记解释其他事情了!_keypressT
的原因和 _keypresst
是这样的,当它作为匿名函数或作为调用堆栈的一部分(有一天会)被调用时,您就可以识别该函数。这是一个非常方便的习惯,可以确保所有潜在的匿名函数仍然被“命名”,即使它们在别处有一个合适的名称。再一次,优秀的 JavaScript 导师建议可以帮助人们的东西 ;-)。
啊!我忘记解释其他事情了!
请注意,您可以轻松地做到:
function doThing() //some pre-defined function before our code
var KeypressFunctions = [];
KeypressFunctions['T'.charCodeAt(0)] = doThing
KeypressFunctions['t'.charCodeAt(0)] = doThing
然后对于 T 或 t,运行 doThing 函数。请注意,我们只是传递了函数的名称,并没有尝试通过 doThing()
来运行该函数。 (这是一个巨大的差异,如果你打算做这种事情,这是一个很大的提示)
真不敢相信我忘了这个!
因为今天的重点是 jQuery,所以这里有一个 block ,您可以在加载 jQuery 库后将其放在应用程序的任何位置(页眉、正文、页脚等):
<script>
function doTheThingsOnKeypress(event){
//do things here! We've covered this before, but this time it's simplified
KeypressFunctions[event.which].call();
}
$(document).on('keypress','selector',doTheThingsOnKeypress);
// you could even pass arbitrary data to the keypress handler, if you wanted:
$(document).on('keypress','selector',{/* arbitrary object here! */},doTheThingsOnKeypress);
//this object is accessible through the event as data: event.data
</script>
如果您要使用 KeypressFunctions
和以前一样,确保它们在此之前实际定义。
关于javascript - 按下键盘键时的JS功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14261062/
我正在构建一个 RCP 应用程序,其中每个季度都会更新功能/插件。因此,如果用户选择自动更新功能/插件,则会下载更新插件的新 jar,但旧插件仍在使用我不再使用的磁盘空间。 我厌倦了删除包含旧 jar
我如何从外部 Controller 功能中调用 Controller 内部的功能,例如电话间隙回调功能 这是 Controller 外部定义的功能 function onDeviceReady()
如果某个功能(例如 MediaSource)可用,我如何使用 Google Dart 检查。 new MediaSource() 抛出一个错误。如何以编程方式检查此类或功能是否存在?有任何想法吗?是否
我正在尝试运行 Azure Orchestrations,突然我开始从 statusQueryGetUri 收到错误: 协调器函数“UploadDocumentOrchestrator”失败:函数“U
我见过 iPhone 上的应用程序,如果在 3.0 上运行,将使用 3.0 功能/API,例如应用内电子邮件编辑器,如果在 2.x 上运行,则不使用这些功能,并退出应用程序以启动邮件相反。 这是怎么做
这是 DB 规范化理论中的一个概念: Third normal form is violated when a non-key field is a fact about another non-ke
如果我定义 #if SOMETHING #endif 而且我还没有在任何地方定义 SOMETHING。 #if 中的代码会编译吗? 最佳答案 当#if的参数表达式中使用的名称未定义为宏时(在所有其他宏
我刚刚澄清了 A* 路径查找应该如何在两条路径具有相等值的 [情况] 下运行,无论是在计算期间还是在结束时,如果有两条相等的短路径。 例如,我在我的起始节点,我可以扩展到两个可能的节点,但它们都具有相
Java有没有类似下面的东西 宏 一种遍历所有私有(private)字段的方法 类似于 smalltalk symbols 的东西——即用于快速比较静态字符串的东西? 请注意,我正在尝试为 black
这个程序应该将华氏度转换为摄氏度: #include int main() { float fahrenheit, celsius; int max, min, step;
当打开PC缓存功能后, 软件将采用先进先出的原则排队对示波器采集的每一帧数据, 进行帧缓存。 当发现屏幕中有感兴趣的波形掠过时, 鼠标点击软件的(暂停)按钮, 可以选择回看某一帧的波形
我有一个特殊的(虚拟)函数,我想在沙盒环境中使用它: disable.system.call eval(parse(text = 'model.frame("1 ~ 1")'), envir = e
使用新的 Service 实现,我是否必须为我的所有服务提供一个 Options 方法? 使用我的所有服务当前使用的旧 ServiceBase 方法,OPTIONS 返回 OK,但没有 Access-
我正在阅读 Fogus 的关于 Clojure 的喜悦的书,在并行编程章节中,我看到了一个函数定义,它肯定想说明一些重要的事情,但我不知道是什么。此外,我看不到这个函数有什么用 - 当我执行时,它什么
我有大量的 C 代码,大部分代码被注释掉和/或 #if 0。当我使用 % 键匹配 if-else 的左括号和右括号时,它也匹配注释掉的代码。 有没有办法或vim插件在匹配括号时不考虑注释掉或#if 0
我有这个功能: map(map(fn x =>[x])) [[],[1],[2,3,4]]; 产生: val it = [[],[[1]],[[2],[3],[4]]] 我不明白这个功能是如何工作的。
我使用 Visual Studio 代码创建了一个函数应用程序,然后发布了它。功能应用程序运行良好。我现在在功能门户中使用代码部署功能(KUDU)并跳过构建。下面是日志 9:55:46 AM
我有一个数据框df: userID Score Task_Alpha Task_Beta Task_Charlie Task_Delta 3108 -8.00 Easy Easy
我真的无法解决这个问题: 我有一个返回数据框的函数。但是,数据框仅打印在我的控制台中,尽管我希望将其存储在工作空间中。我怎样才能做到这一点? 样本数据: n <- 32640 t <- seq(3*p
有没有办法找出所有可能的激活器命令行选项? activator -help仅提供最低限度的可用选项/功能列表,但所有好的东西都隐藏起来,即使在 typesafe 网站在线文档中也不可用。 到目前为止,
我是一名优秀的程序员,十分优秀!