【问题标题】:jQuery UI Dialog will not openjQuery UI 对话框不会打开
【发布时间】:2026-01-24 20:30:01
【问题描述】:

我正在尝试调出一个 jQuery UI 对话框来响应表单输入。考虑:

<html>
   <head>
      <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> 
      <script src="checkLogin.js"></script>
   </head>
   <body>
      <form>
         <label>User Name:</label><input onkeydown="checkSubmitKey(event)"><br>
         <input id="submit" name="submit" type="button" onclick="checkLogin()" value="Submit">
      </form>
      <div id="dialog" title="Alert" style="display: none;"></div>
   </body>
</html>

checkLogin.js 在哪里:

function checkSubmitKey(ev) {
    if(ev.keyCode == 13) {
        checkLogin();
    }
}

function checkLogin() {
   showAlert("Hello");
}

function showAlert(str) {
    $( "#dialog" ).html(str);
    $( "#dialog" ).dialog({
        modal: true,
        title: "Alert",
        buttons: {
            "OK": function() {
                $( this ).dialog( "close" );
            }
        }
    });
}

问题是对话框只在我按下“提交”按钮时显示;如果我在“用户名”文本字段中按 Enter,则没有任何反应。

(如果我将函数 checkLogin 更改为

function checkLogin() {
   alert("ok");
   showAlert("Hello");
}

当我按下 Enter 时也会出现对话框。)

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您需要阻止 Enter 键的默认操作。把JS改成:

    function checkSubmitKey(ev) {
        if(ev.keyCode == 13) {
            ev.preventDefault();
            checkLogin();
        }
    }
    

    FIDDLE

    【讨论】:

    • 只是好奇:必须防止的默认行为到底是什么?为什么这种行为会阻止对话框出现?
    最近更新 更多