admin管理员组

文章数量:1419640

Console.log is printed twice. I have tried using e.stopPropagation(),e.preventDefault() and .stop(). It does not work. The console.log should trigger only once

$('html').keyup(function (e) {
    if (e.keyCode == 46) {
        console.log("delete press");
        e.stopPropagation();
        e.preventDefault();
    }
});

Console.log is printed twice. I have tried using e.stopPropagation(),e.preventDefault() and .stop(). It does not work. The console.log should trigger only once

$('html').keyup(function (e) {
    if (e.keyCode == 46) {
        console.log("delete press");
        e.stopPropagation();
        e.preventDefault();
    }
});
Share Improve this question edited Jan 9, 2019 at 7:20 Monica Acha 1,0869 silver badges16 bronze badges asked Jan 9, 2019 at 6:45 J. DoeJ. Doe 951 gold badge2 silver badges11 bronze badges 3
  • 1 "console.log will be only trigger once" Then how do you know the event is triggered twice? Also, stopping event propagation on HTML element does nothing, an event can't bubble out of the document anyway. – Teemu Commented Jan 9, 2019 at 6:54
  • 2 Not enough information. Posted code can't behave like you described. – dfsq Commented Jan 9, 2019 at 6:54
  • Can you try .unbind and then .bind. It could be that the event has been bound twice? – Colwin Commented Jan 9, 2019 at 6:55
Add a ment  | 

3 Answers 3

Reset to default 5

I had a similar problem a while back. I ended up using $.unbind() and $.bind(). I would first call $.unbind() to remove any callback functions to the event that were potentially already bound to event. Then, I would call $.bind() on the event so it can do what I want it to do.

$('html').unbind('keyup');
$('html').bind('keyup', function (e) {

You probably need to debounce the event.

You can use something like lodash to do this easily, or you can roll your own if you want to learn how it works.

function handler(e) {
    if (e.keyCode == 46) {
        console.log("delete press");
        e.stopPropagation();
        e.preventDefault();
    }
}
$('html').keyup(lodash.debounce(handler, 250));

250 here is the number of milliseconds to debounce an event, also notice how the event is wrapped.

The documentation for all the options can be found here: https://lodash./docs/4.17.11#debounce

Detaching the event with off() also works

 $('html').off('keyup').on('keyup',function (e) {
  if (e.keyCode == 46) {
    console.log("delete press");
    e.stopPropagation();
    e.preventDefault();
  }
});

OR

execute the event handler only once using one() as

$('html').one('keyup',function (e) {
if (e.keyCode == 46) {
    console.log("delete press");
    e.stopPropagation();
    e.preventDefault();
}

});

本文标签: javascriptHow to stop Keyup event from triggering twiceStack Overflow