【问题标题】:jQuery keypress duplicatejQuery按键重复
【发布时间】:2018-07-16 23:57:10
【问题描述】:

我正在尝试显示用户使用 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”。为什么密钥被复制?

【问题讨论】:

    标签: jquery html keypress


    【解决方案1】:

    问题出在您的* 选择器中,它同时应用于&lt;body&gt;&lt;html&gt;

    只需将特异性提高到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>

    【讨论】:

    • 非常感谢!!我应该知道简单的* 会回来困扰我。
    猜你喜欢
    • 1970-01-01
    • 2011-05-05
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2019-09-25
    相关资源
    最近更新 更多