【问题标题】:How to call a function when enter key pressed? [duplicate]按下回车键时如何调用函数? [复制]
【发布时间】:2014-10-12 13:25:50
【问题描述】:
<input type="email" name="email" id="email" style="width:100%;" onkeypress="getMailList($('#email').val())" required>

我只需要在按下回车键时调用一个函数。我只是使用kepress事件。但它调用函数所有按键。提前致谢。

【问题讨论】:

标签: javascript html


【解决方案1】:

HTML:

<input id="typeHere" placeholder = "Type here and Press Enter" type="text" onkeypress="return functionCall(event)"></input>

jquery:

var functionCall= function(e) {
    if (e.keyCode == 13) {
        var tb = document.getElementById("typeHere");
        alert(tb.value);
        return false;
    }
    else {
     return true;
    }
}

见小提琴here

【讨论】:

    【解决方案2】:

    每个人都建议使用 jQuery,在这种情况下根本不需要它。 更多的 javascript 也是如此,它不是必需的,并且可能会使您的代码可读性降低。

    您唯一需要做的就是在 html 标记中添加一个 if 语句。

    只需添加以下 if 语句:

    if (window.event.keyCode == 13) getMailList($('#email').val())
    

    13 是输入的键码。

    <input type="email" name="email" id="email" style="width:100%;" 
    onkeypress="if (window.event.keyCode == 13) getMailList($('#email').val())" required>
    

    【讨论】:

      【解决方案3】:

      有两种方法:

      1. 在输入上绑定您的事件 onkeypress,检查按下的键是否为“输入”(字符代码 = 13)
      2. 将您的事件绑定到周围表单上的 onSubmit 事件。 onSubmit 事件会在按下回车时触发。

      后者的一个示例,它更好,因为它允许您在禁用 javascript 时使其工作:

      <form action="/foo/bar" method="post" id="form">
          <input type="email" id="email" name="email" required />
      </form>
      
      $('#form').on('submit', function(e) {
          e.preventDefault();
          getMailList($('#email').val());
          // do something else
      });
      

      【讨论】:

        【解决方案4】:

        好像您已经在使用 jquery,所以试试下面的代码:

        $('#email').keypress(function(e) {
            if(e.which == 13) {
              var email = $(this).val();
              getMailList(email);
            }
        });
        

        【讨论】:

          【解决方案5】:

          如果你想使用 jQuery:

          $("#email").keyup(function(event){
            if(event.keyCode === 13){
                //Do something
            }
          });
          

          13 是回车键码(其他键码:http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html

          【讨论】:

            猜你喜欢
            • 2015-08-22
            • 2019-11-29
            • 2011-06-22
            • 2016-09-03
            • 2015-02-11
            • 1970-01-01
            • 2021-05-21
            • 2023-04-06
            • 1970-01-01
            相关资源
            最近更新 更多