代码之家  ›  专栏  ›  技术社区  ›  Kaisin Li

jQuery按键输入不工作

  •  3
  • Kaisin Li  · 技术社区  · 7 年前

    <p>words words words <i>test</i> more words</p>
    <div id="newWord">
       <form>
          <input type="text" placeholder="New Hashtag"></input>
       </form>
    </div>
    

    $(document).ready(function () {
        $("input").keypress(
            function (e) {
                var currentInput = $("input").val();
                console.log(currentInput);
                if (e.keyCode === 13) {
                    console.log('hello');
                }
            }
        );
    })
    

    我的控制台日志没有登录第一个按键,我该怎么做?还有我的“你好”从来没有记录。知道为什么会这样吗?

    谢谢

    3 回复  |  直到 7 年前
        1
  •  5
  •   Muthu Kumaran    7 年前

    keyup

    $(document).ready(function () {
        $("input").keyup(
            function (e) {
                var currentInput = $("input").val();
                console.log(currentInput);
                if (e.keyCode === 13) {
                    console.log('hello');
                    alert('hello');
                }
            }
        );
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>words words words <i>test</i> more words</p>
    <div id="newWord">
      <form>
        <input type="text" placeholder="New Hashtag">
      </form>
    </div>
        

    Enter

        2
  •  0
  •   Dan Barbarito    7 年前

    keypress 当按下一个键时,该函数将立即启动。您想要使用 keyup

        3
  •  0
  •   brk    7 年前

    你需要使用 keyup 因为按键会在按下一个键时触发值,该键与释放一个键是分开的。

    input $(this) 在函数内部,因为它将仅从触发事件的输入中获取值。

    enter/return 您可能会看到表单正在提交

    $(document).ready(function() {
      $("input").keyup(function(e) {
        var currentInput = $(this).val();
        console.log(currentInput);
        if (e.keyCode == 13) {
          console.log('hello');
        }
      });
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>words words words <i>test</i> more words</p>
    <div id="newWord">
      <form>
        <input type="text" placeholder="New Hashtag">
      </form>
    </div>