简体   繁体   English

在 keyup 事件中检测 Ctrl + A

[英]Detect Ctrl + A in keyup event

I want to detect the Control + A event in input.我想检测输入中的Control + A事件。 I can find the Control + A event, but the function is continuing even after return false .我可以找到Control + A事件,但即使在return false之后该功能仍在继续。

jsFiddle - http://jsfiddle.net/f6rcgpmh/4/ jsFiddle - http://jsfiddle.net/f6rcgpmh/4/

 $('.searchTerm').keyup(function(e) { $("#status").text(""); if (e.ctrlKey) { if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a' console.log("Control pressed"); e.preventDefault(); return false; } } $("#status").text("This should not work if Ctrl + A is pressed"); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="search" class="search"> <input class="searchTerm" placeholder="Filter Books..."> <input class="searchButton" type="submit"> </form> <div id="status"></div>

I want this to work in keyup not in keydown .我希望它在keyup而不是在keydown Because I am using autosearch and I don't want to call function before keyrelease.因为我正在使用自动搜索并且我不想在 keyrelease 之前调用函数。 And also Ctrl + A won't highlight text in keydown when it returned false.而且Ctrl + A在返回 false 时不会突出显示 keydown 中的文本。

Actually the function stops.实际上功能停止了。 What you are experiencing is that two keyup events trigger: the one from ctrl and the one from A .您遇到的是两个 keyup 事件触发:一个来自ctrl ,另一个来自A

The first one returns as expected because it does fill the requirements: ctrlKey == true and keyCode == 65 || keyCode == 97第一个按预期返回,因为它确实满足要求: ctrlKey == truekeyCode == 65 || keyCode == 97 keyCode == 65 || keyCode == 97 . keyCode == 65 || keyCode == 97

But the second one, there will be only one key pressed so both statements can't be true together:但是第二个,只会按下一个键,所以这两个陈述不能同时成立:

  • If you last released the ctrl , then ctrlKey is true but keyCode == 65 || keyCode == 97如果您上次释放ctrl ,则ctrlKey为真但keyCode == 65 || keyCode == 97 keyCode == 65 || keyCode == 97 is not. keyCode == 65 || keyCode == 97不是。

  • If you last released the A , then ctrlKey is now false.如果您上次释放了A ,则ctrlKey现在为 false。

Then the line which sets #status to an error message is run.然后运行将#status设置为错误消息的行。

Actually it's not.其实不是。 You must change your event from 'keyup' to 'keydown' .您必须将事件从'keyup'更改为'keydown' Then try it again.然后再试一次。 You can check this fiddle.你可以检查这个小提琴。 http://jsfiddle.net/ebilgin/f6rcgpmh/5/ http://jsfiddle.net/ebilgin/f6rcgpmh/5/


If you need control on autocomplete, you have to put your controls before sending the data.如果您需要控制自动完成,您必须在发送数据之前放置您的控件。

The Ctrl keyup event trigger causes your problem. Ctrl keyup 事件触发器会导致您的问题。 I added another condition to your code,我在你的代码中添加了另一个条件,

if (e.keyCode == 17) // Ctrl key, fires at Ctrl's keyup.
    return false;

You can check my new fiddle, http://jsfiddle.net/ebilgin/f6rcgpmh/10/ .你可以检查我的新小提琴, http://jsfiddle.net/ebilgin/f6rcgpmh/10/

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

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