简体   繁体   English

jQuery模式弹出窗口中的按键

[英]keypress in jquery modal popup

I opened a jquery modal dialog which has 2 textboxes and a button 我打开了一个有两个文本框和一个按钮的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>

now in my script I'm calling LogIn function 现在在我的脚本中,我正在调用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();
}

but keypress is not fired..any ideas why and what is possible solution for that? 但没有触发按键..任何想法为什么以及对此的可能解决方案?

You need to use event-delegation on dynamically created elements 您需要在动态创建的元素上使用事件委托

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

try to use the Keydown or Keyup events instead: 尝试改用Keydown或Keyup事件:

$(function () {

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

    }
});

I find it a better solution to give focus to the modal, it worked for me. 我发现将焦点放在模式上是一个更好的解决方案,它为我工作。

In order to do that, you have to add a tabindex parameter to your modal container, and then set its focus using JavaScript. 为此,您必须向模式容器中添加一个tabindex参数,然后使用JavaScript设置其焦点。 Once that's done it can receive keyboard events: https://stackoverflow.com/a/6633271/2873507 完成后,它可以接收键盘事件: https : //stackoverflow.com/a/6633271/2873507

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM