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
3 Answers
Reset to default 5I 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
版权声明:本文标题:javascript - How to stop Keyup event from triggering twice - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745309444a2652849.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论