【问题标题】:How fire up input textbox keypress event using with jquery without typing如何在不输入的情况下使用 jquery 启动输入文本框按键事件
【发布时间】:2017-06-14 11:21:37
【问题描述】:

我想使用 jquery 启动输入文本框 keypress 事件而不输入。
看看这个 sn-p :

var e = jQuery.Event("keypress");
e.keyCode = $.ui.keyCode.ENTER;
$("input").trigger(e);

这有什么要求吗?
但是这些代码有错误:

无法读取 undefiend 的属性 'which'

如何绕过该错误并使用 jquery 启动输入文本框 keypress 事件而无需输入?


我也试过这个:
$('#input').val('string');
$('#input').keypress();

同样的错误

【问题讨论】:

    标签: jquery events keypress


    【解决方案1】:

    要使$.ui.keyCode 工作,您需要包含jquery-ui.js

    没有jquery-ui

    $(function(){
      var e = $.Event("keypress");
      e.which = 13;
      $('input').trigger(e);
    });
    
    $('input').on('keypress',function(e){
      if(e.which==13)
        alert('Enter pressed automatically');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" />

    jquery-ui

    $(function(){
      var e = $.Event("keypress");
      e.which = $.ui.keyCode.ENTER;
      $('input').trigger(e);
    });
    
    $('input').on('keypress',function(e){
      if(e.which==13)
        alert('Enter pressed automatically');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
    
    <input type="text" />

    【讨论】:

    【解决方案2】:

    将此解决方案与 jquery 一起使用

    $(document).ready(function() {
        var e = $.Event("keypress", {which: 13});
        $('input').trigger(e);
    });
    $('input').on('keypress',function(e){
        console.log(e.which+' -- KeyPress event Fired');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 2013-01-01
      • 1970-01-01
      相关资源
      最近更新 更多