gpt4 book ai didi

javascript - 文本字段上的 onKeypress Enter Key 事件在 Chrome 中不起作用

转载 作者:行者123 更新时间:2023-11-29 15:47:36 25 4
gpt4 key购买 nike

我有一个与 the one asked here 相同的问题关于如何在 chrome 中处理回车键。

我想要实现的效果是允许 enter 键在焦点位于当前字段内时调用一个按钮的单击事件。为此,我使用了以下代码:

JavaScript:

 <script type="text/javascript">
//attempting to capture keypress for chrome here but this is not working
$("#txtContainer").keypress(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
doClick(buttonname, e);
return false;
}
});

function doClick(buttonName, e) {

var key;
if (window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox

if (key == 13) {
var btn = document.getElementById(buttonName);
if (btn != null) {
btn.click();
event.keyCode = 0
}
}
}
</script>

在aspx中

 <form id="form1" runat="server">
<div>
<asp:LinkButton ID="newBtn" runat="server" OnClick="btnLogin_Click" Text="ASP Link" />
<asp:TextBox ID="txtContainer" runat="server" Width="100" />
<asp:Label ID="time_lbl" runat="server" />
</div>
</form>

在后面的代码中aspx.cs

 protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtContainer.Attributes.Add("onKeyPress", "doClick('" + newBtn.ClientID + "',event)");
}

}

public void btnLogin_Click(object sender, EventArgs e)
{
time_lbl.Text = txtContainer.Text;
}

上面的代码在 FF 和 IE 中工作正常,但是 chrome 继续提交整个表单而不是捕获回车键上的按键。

感谢您的任何建议。

最佳答案

我会说使用“keyup”而不是“keypress”应该可以解决您的问题

关于javascript - 文本字段上的 onKeypress Enter Key 事件在 Chrome 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9284847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com