admin管理员组

文章数量:1291142

I have keyup/down events binded to the document. The Keydown will only fires every second time, without me knowing why. I tried many suggestions given on similar SO-Questions, but none of them works.

My Javascript:

$(document).on('keyup', function() {
    $('div').removeClass('bar');
});
$(document).on('keydown', function(e) {
    if(e.altKey) {
        $('div').addClass('bar');  // only every second hit will add the class
    }
});

This should point out the issue: /

I have keyup/down events binded to the document. The Keydown will only fires every second time, without me knowing why. I tried many suggestions given on similar SO-Questions, but none of them works.

My Javascript:

$(document).on('keyup', function() {
    $('div').removeClass('bar');
});
$(document).on('keydown', function(e) {
    if(e.altKey) {
        $('div').addClass('bar');  // only every second hit will add the class
    }
});

This should point out the issue: http://jsfiddle/6yxt53m9/1/

Share Improve this question asked Sep 18, 2014 at 8:59 JonathanJonathan 2,0735 gold badges31 silver badges54 bronze badges 4
  • Do you have to use the alt key? – artm Commented Sep 18, 2014 at 9:01
  • Works the first time for me under ubuntu and chrome – Brewal Commented Sep 18, 2014 at 9:01
  • Yes it must be the alt key – Jonathan Commented Sep 18, 2014 at 9:02
  • I'm on Chrome at Mac, but this fiddle is working fin for me. – Sameera Thilakasiri Commented Sep 18, 2014 at 9:06
Add a ment  | 

3 Answers 3

Reset to default 7

You need to add return false; to the key press functions:

$(document).on('keyup', function() {
    $('div').removeClass('bar');
    return false;
});

$(document).on('keydown', function(e) {
    if(e.altKey) {
        $('div').addClass('bar');
    }
    return false;
});

Updated fiddle.

use

$(document).on('keyup', function(e) {
    $('div').removeClass('bar');
    e.preventDefault();
});

e.preventDefault(); will reset the input

Try this.

$(document).on('keydown', function(e) {
    e.preventDefault();
    if(e.altKey) {
        $('div').addClass('bar');  // only every second hit will add the class
    }
});

The reason is alt key occurs focus moving to button of "customize and control google chorome"

本文标签: javascriptjQuery KeydownKeyup only works every second timeStack Overflow