2014-06-29 119 views
0

我想調出一個jQuery UI對話框來響應表單輸入。試想一下: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"); 
      } 
     } 
    }); 
} 

的問題是,當我按下 「提交」 按鈕關閉對話框只顯示;如果我按在「用戶名」文本字段中輸入,則什麼都不會發生。

(如果我改變功能checkLogin

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

的對話框當我按下回車出現。)

回答

1

您需要防止的默認操作輸入鍵。更改JS到:

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

FIDDLE

+0

謝謝!這工作:) –

+0

只是好奇:什麼是必須防止的默認行爲?爲什麼這種行爲會阻止對話出現? –