如何阻止 Keyup 事件触发两次

J. *_*Doe 0 javascript jquery

Console.log 打印两次。我曾尝试使用 e.stopPropagation()、e.preventDefault() 和 .stop()。这是行不通的。console.log 应该只触发一次

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

小智 5

不久前我遇到了类似的问题。我最终使用了$.unbind()$.bind()。我会首先调用$.unbind()删除可能已经绑定到事件的事件的任何回调函数。然后,我会调用$.bind()该事件,以便它可以做我想要它做的事情。

$('html').unbind('keyup');
$('html').bind('keyup', function (e) {
Run Code Online (Sandbox Code Playgroud)