jQuery 按键重复

jQuery keypress duplicate

我正在尝试显示用户使用 jQuery 检测到的按键输入的内容。

例如,如果用户按下 "a",则显示 "a"。当他们然后按 "z" 时,会显示 "az",依此类推。

我的代码:

<script>
    $(document).ready(function() {
        var res = "";

        $("*").keypress(function( event ) {
            res = res + String.fromCharCode(event.which);
            $("#go2").html(res);
        });
    });
</script>


<p id="go2"></p>

显示 String.fromCharCode(event.which) 而不是 res 正确显示按下的键,但是当前代码重复了这些键。

当我按下 "a" 时,会显示 "aaa"。按 "z" 等新键,然后显示 "aaazzz"。为什么密钥被复制?

问题出在您的 * 选择器中,它同时应用于 <body><html>

只需将特异性提高到 body 就会导致重复消失:

$(document).ready(function() {
  var res = "";
  $("body").keypress(function(event) {
    res = res + String.fromCharCode(event.which);
    $("#go2").html(res);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="go2"></p>