2013-05-17 191 views
3

當我打開一個jQuery UI對話框小部件,並且對話框中的內容包含一個文本框時,當我按下回車鍵時,對話框自動關閉。這似乎只在使用IE9或IE10時纔會發生。當我按下文本框中的輸入時,我不希望對話框關閉。jQuery UI對話框關閉輸入

我有以下HTML:

<!DOCTYPE html> 

<html> 

<head> 
<title>Testpage</title> 

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#myDialog').dialog(); 
    }); 
</script> 

</head> 

<body> 

    <div id="myDialog"> 
     Some text   
     <input type="text"></input> 
    </div> 

</body> 
</html> 

當您打開該HTML頁面,當你按下(僅在IE9 +)輸入對話框將關閉。有什麼建議麼?

+0

[這](http://jsfiddle.net/SirDerpington/3FVsp/)的jsfiddle似乎很好地工作。 ..即使在IE 10和9 – SirDerpington

+0

當我使用你的jsFiddle按下輸入文本框打開另一個頁面,就像有某種形式的提交。 Chrome和Firefox中不顯示此行爲。當我在文本框中按回車鍵時,我想讓對話框什麼也不做。 – Barbarammie

+0

小提琴沒有使用上面看到的相同版本的jQuery UI。 –

回答

3

它看起來像在jQuery UI 1.10.x右上角的關閉按鈕從<a>更改爲<button>。由於此按鈕沒有指定type屬性,因此它被認爲是type="submit"。當您在IE9 +中按Enter時,瀏覽器會查找提交按鈕,找到關閉按鈕並按下它。

有幾個方法可以解決這個問題,我認爲,最好的辦法就是通過覆蓋ui.dialog的_init功能修正關閉按鈕的類型:

var baseInit = $.ui.dialog.prototype._init; 
$.ui.dialog.prototype._init = function() { 
    baseInit.apply(this, arguments); 

    // Make the close button a type "button" rather than "submit". This works 
    // around an issue in IE9+ where pressing enter would trigger a click of 
    // the close button. 
    $('.ui-dialog-titlebar-close', this.uiDialogTitlebar).attr('type', 'button'); 
}; 
+0

沒有必要在init對話框中創建這個補丁。 –

+3

@Leandro你能提供更多細節嗎? –

1

如果對話框沒有需要被autoopened,對話框被創建後,它的開業前:

 $("button.ui-dialog-titlebar-close").attr("type","button");  

另外,如果你有在對話框HTML的任何按鈕元素,一定要明確包括的類型= 「按鈕」屬性,或者在輸入中放置控件將觸發與按鈕相關的操作。

0

IE9/IE10和IE11之間的區別似乎是,ie9和10在keydown上激活,而11則激活了keyup上的提交按鈕。

如果您正在處理keyup採取自己的行動,它將適用於大多數瀏覽器...除了9-10。另一種解決方案是重寫的keydown,但要小心,仍然允許某些控制,以獲得進入關鍵:

$(document).on('keydown', '.ui-dialog', function (e) { 
    var tagName = e.target.tagName.toLowerCase(); 
    if (e.which !== $.ui.keyCode.ENTER) return true; 
    if (tagName === 'textarea') return true; 
    if (tagName === 'select') return true; 
    e.preventDefault(); 

    return false; 
});