我一直在使用帶有onserverclick屬性的html按鈕時遇到了一些非常奇怪的行爲。我想要做的是使用jQuery來指定頁面上的默認按鈕。默認情況下,按鈕我的意思是當用戶點擊輸入時「點擊」按鈕。在測試中,我會在輸入字段中輸入,有時會單擊預期的「默認」按鈕,並在相應的onserverclick屬性中定義服務器端方法。其他時候,回發沒有觸及服務器方法。爲了隔離這個問題,我創建了一個最小的測試用例,並發現了一些非常有趣的結果。asp.net中的html按鈕元素和onserverclick屬性
客戶端:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="/scripts/jquery-1.4.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="_response" runat="server"></asp:Label>
<input id="input1" type="text" />
<input id="input2" type="text" />
<button id="first" type="button" class="defaultBtn" runat="server" onserverclick="ServerMethod1">test1</button>
<button id="second" type="button" runat="server" onserverclick="ServerMethod2">test2</button>
</form>
<script type="text/javascript">
jQuery('form input').keyup(
function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button.defaultBtn').click();
return true;
}
}
);
</script>
</body>
</html>
服務器端:
public partial class admin_spikes_ButtonSubmitTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ServerMethod1(object sender, EventArgs e)
{
_response.Text = "server method1 was hit";
}
protected void ServerMethod2(object sender, EventArgs e)
{
_response.Text = "server method2 was hit";
}
}
我發現的是,一切都按這個代碼除了當我刪除輸入要素之一預期。在Firefox 3.6和IE 8中,當頁面上只有一個輸入時,按回車鍵不會觸發onserverclick,它甚至不會被jQuery「點擊」或實際「點擊」回發。您可以通過從兩個輸入開始並單擊「test2」來測試此項。這將輸出「服務器method2被擊中」。然後敲回車,輸出將是「服務器method1被擊中,現在拿走一個輸入並運行相同的測試,點擊」test2「查看結果,然後按回車,你會發現沒有什麼會改變,因爲」test1「方法從不打沒有人知道是怎麼回事
感謝
PS鉻和預期一樣
nope仍然遇到相同的行爲。我認爲我的測試指出,當有一個輸入時,這個按鍵事件甚至沒有被解僱。該頁面剛剛提交。感謝您嘗試通過 – 2010-02-02 05:41:40
嘗試替換:
您的解決方案,但現在我沒有與HTML按鈕標籤的CSS靈活性,因爲asp:按鈕呈現爲輸入類型=提交 – 2010-02-02 06:17:18