按下回车键时调用特定按钮的 onClick 事件 C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/268588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:51:28  来源:igfitidea点击:

Call a specific button onClick event when the enter key is pressed C#

c#onclickkeypressenter

提问by Static Tony

I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.

当我在特定的 asp:textbox 控件中按下 Enter 键时,我试图让特定的 asp:button onclick 事件触发。

The other factor to be taken into account is that the button is within a asp:Login control template.

另一个要考虑的因素是按钮位于 asp:Login 控件模板中。

I've no idea how to do this, suggestions on a postcard please.

我不知道如何做到这一点,请在明信片上提出建议。

采纳答案by k?e?m?p? ?

You could look at the DefaultButtonproperty of the panel control.

您可以查看DefaultButton面板控件的属性。

回答by Andrew Bullock

You need to do it with javascript. It's really easy with jQuery.

你需要用javascript来做。使用jQuery真的很容易

You can do something like (off the top of my head, not tested):

您可以执行以下操作(在我的脑海中,未测试):

$('#myTextBox').keypress(function(e){
    if(e.which == 13)
        $('#myBtn').click();
});

Edit: Be aware that although jQuery works exceptionally cross browser, there are some quirks with keypress described here.

编辑:请注意,尽管 jQuery 在跨浏览器上工作得非常出色,但此处描述的按键有些怪癖。

Whoops i didnt see you said the "enter key" i thought you said "any key", yeah in that case use DefaultButton on asp:panel

哎呀,我没看到你说“输入键”,我以为你说的是​​“任意键”,是的,在这种情况下,请在 asp:panel 上使用 DefaultButton

回答by Andrew Van Slaars

You could set the DefaultButton property on the form. Either as an attribute of the form tag in your markup DefaultButton = "btnSubmit" or using something like this in your code-behind:

您可以在表单上设置 DefaultButton 属性。作为标记中的表单标记的属性 DefaultButton = "btnSubmit" 或在您的代码隐藏中使用类似的东西:

Page.Form.DefaultButton = "btnSubmit"