【问题标题】:keypress in jquery modal popupjquery模式弹出窗口中的按键
【发布时间】:2019-07-18 22:21:09
【问题描述】:

我打开了一个带有 2 个文本框和一个按钮的 jquery 模态对话框

<table cellpadding="0" cellspacing="0">
        <tr>
          <td align="center"><input name="" type="text" value="" title="User Name" class="width190 enter_popup" id="txtUserName" onfocus="txtFocus(this)" onblur="txtFBlur(this,'0')"/></td>
          <td align="center"><input name="" type="password" value=""  title="Password" class="width190 enter_popup" id="txtPassword" onfocus="txtFocus(this)" onblur="txtFBlur(this,'1')"/></td>
        </tr>
        <tr>
          <td colspan="2" align="center"><input name="" type="submit" class="blue_btn" value="Sign In"  id="btnLogIn" onclick="javascript:return LogIn()"/></td>
        </tr>

      </table>

现在在我的脚本中我正在调用 LogIn 函数

$(function () {

    $(".enter_popup").keypress(function (e) {
        if (e.keyCode == 13) {
            if ($(this).attr('id') == "txtUserName" || $(this).attr('id') == "txtPassword") {
                LogIn();
            }

        }
    });
 });

function LogIn() {
    var username = $('#txtUserName').val();
    var password = $('#txtPassword').val();
}

但是按键没有被触发..任何想法为什么以及可能的解决方案是什么?

【问题讨论】:

  • 在这里工作正常jsfiddle.net/dzxu1c8s 所以我猜该元素是动态创建的,因此需要event-delegation $(document).on('keypress','.enter_popup',function(){/*code*/});
  • 还验证了您的代码正在运行。试试上面安东的解决方案。
  • @Anton:这个$(document).on('keypress','.enter_popup',function(){/*code*/}); 为我工作.. 将其作为答案发布。

标签: javascript jquery asp.net-mvc-3 jquery-dialog


【解决方案1】:

您需要对动态创建的元素使用事件委托

$(document).on('keypress','.enter_popup',function(){
    /*Your code*/
});

【讨论】:

    【解决方案2】:

    尝试改用 Keydown 或 Keyup 事件:

    $(function () {
    
    $(".enter_popup").keyup(function (e) {
        if (e.keyCode == 13) {
            if ($(this).attr('id') == "txtUserName" || $(this).attr('id') == "txtPassword") {
                LogIn();
            }
    
        }
    });
    

    【讨论】:

      【解决方案3】:

      我发现将重点放在模态上是一个更好的解决方案,它对我有用。

      为此,您必须向模态容器添加tabindex 参数,然后使用JavaScript 设置其焦点。完成后,它可以接收键盘事件:https://stackoverflow.com/a/6633271/2873507

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多