【问题标题】:Use an enter key to perform a text field function使用回车键执行文本字段功能
【发布时间】:2016-10-16 13:23:05
【问题描述】:

我尝试使用的代码。请告诉我我做错了什么。我不是很擅长 JavaScript,所以不要评判。

<!-- Textfield with Floating Label -->

<form action="#">
  <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(e)">
    <label class="mdl-textfield__label" for="userInput">Answer Here</label>
  </div>
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that rusn
var input = document.getElementById("userInput").value;
    alert(input);
        }
    }
</script>
    </body>
</html>

【问题讨论】:

    标签: javascript html textfield keypress


    【解决方案1】:

    您可能想通过活动,而不仅仅是e

    <input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)">
    

    <form action="#">
        <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
            <input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)">
            <label class="mdl-textfield__label" for="userInput">Answer Here</label>
        </div>
    </form>
    
    <script>
        function handle(e) {
            if (e.keyCode === 13) {
                e.preventDefault(); // Ensure it is only this code that rusn
                var input = document.getElementById("userInput").value;
                alert(input);
            }
        }
    </script>

    你最好改用addEventListener

    document.getElementById('userInput').addEventListener('keypress', function(e) {
        if(e.keyCode === 13) {
            e.preventDefault();
            var input = this.value;
            alert(input);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2013-03-07
      • 1970-01-01
      • 2015-01-17
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2014-02-18
      相关资源
      最近更新 更多