Javascript 用 jQuery 中的 TAB 键代码替换 Enter 键代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10408811/
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
replacing Enter key code with TAB key code in jQuery
提问by Arian
I have a script in javascript that replace Enterwith TABkey:
我在 javascript 中有一个Enter用TAB键替换的脚本:
function ReplaceEnterWithTab() { if (event.keyCode == 13) event.keyCode = 9; return false; }
and I use it this way:
我这样使用它:
txt.Attributes.Add("OnKeyDown", "ReplaceEnterWithTab();");
this code work nice.Now I want to develop a script with jQuery that will not need to add OnKeyDown
attribute.please consider this sample page:
这段代码很好用。现在我想用 jQuery 开发一个不需要添加OnKeyDown
属性的脚本。请考虑这个示例页面:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="EntTab"></asp:TextBox>
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server" CssClass="EntTab"></asp:TextBox>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="EntTab">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
I write this code :
我写了这段代码:
$(document).ready(function () {
$('.EntTab').on('keydown', function (e) {
if (e.keyCode == 13) e.keyCode = 9;
});
});
the problem is when I press Enterkey on TextBox1
, Button1
cause page post back. How I can solve this issue?
问题是当我按下Enter键时TextBox1
,Button1
导致页面回发。我该如何解决这个问题?
thanks
谢谢
回答by Sudhir Bastakoti
Try:
尝试:
$(document).ready(function () {
$(".EntTab").bind("keypress", function(e) {
if (e.keyCode == 13) {
var inps = $("input, select"); //add select too
for (var x = 0; x < inps.length; x++) {
if (inps[x] == this) {
while ((inps[x]).name == (inps[x + 1]).name) {
x++;
}
if ((x + 1) < inps.length) $(inps[x + 1]).focus();
}
} e.preventDefault();
}
});
});
Did you mean something like that.
你是不是这个意思。
回答by Artem Koshelev
You forgot to cancel the event propagation, add return false
to the keydown callback:
您忘记取消事件传播,添加return false
到 keydown 回调中:
$(document).ready(function () {
$('.EntTab').on('keydown', function (e) {
if (e.keyCode == 13) e.keyCode = 9;
return false;
});
});
Also, Button tag in ASP.NET has UseSubmitBehavior
flag set to trueby default, which causes the button to be rendered as input type="submit"
tag. Try setting it to false, to get the behavior like described in the following answer: Use Javascript to change which submit is activated on enter key press
此外,ASP.NET 中的 Button 标记默认UseSubmitBehavior
设置为 true,这会导致按钮呈现为input type="submit"
标记。尝试将其设置为 false,以获得如下答案中所述的行为:使用 Javascript 更改在输入键按下时激活哪个提交