jquery: keydown, keyup, small snippet, why isn't this working?
Why isn't this working?
var holdingctrl = false;
$(document).keydown("q",fun开发者_StackOverflow社区ction(e) {
if(holdingctrl == true)
alert("Holding CTRL and pressing Q: Success.");
e.preventDefault();
});
$(document).keyup("q",function(e) {
holdingctrl == false
});
This example below works just fine, but what am i doing wrong above?
$(document).keyup("q",function(e) {
alert("ONLY pressing Q: Success.");
});
You needed a way to determine if control was currently being pressed (e.ctrlKey) - This should work for you:
$(document).keyup(function(e)
{
if (e.ctrlKey && e.keyCode == 81)
{
alert("CTRL+Q Pressed");
}
});
Working Demo here
Depends on what you're trying to accomplish.
Couple notes:
- the event data you're passing should be an object instead of a single character.
- the
keyup
handler isn't doing anything with the==
comparison. You probably meant to use an=
assignment.
$(document).keyup( { theChar:"q" }, function(e) {
holdingctrl = false;
});
I'm not entirely sure what you're trying to do with this snippet, but you can check whether ctrl is pressed by using the event.ctrlKey
property:
$(document).keydown(function(e) {
if (e.ctrlKey && (e.keyCode == 81)) { // ctrl + q
alert("Pressing Q and ctrl: Success.");
}
});
精彩评论