Mar*_*ieB 40 jquery textbox enter keycode button
我试图让Enter键在某个文本框内按下时触发一个函数,而不是触发第一个或默认按钮.
你可以看到这里发生的事情的一个例子:http://jsfiddle.net/cutsomeat/WZ6TM/1/
如果按其他键,您将收到一个带有键码的警告框,但是如果您按下Enter键,您将无法获得带有键码的警告框,而是按钮点击事件中的警告框.
显然,Enter键是触发按钮.有没有办法避免这种情况,而是在keyup事件中捕获Enter键,然后触发另一个函数?
sac*_*een 87
试试这个:
$('#myText').on("keypress", function(e) {
if (e.keyCode == 13) {
alert("Enter pressed");
return false; // prevent the button click from happening
}
});
Run Code Online (Sandbox Code Playgroud)
Arv*_*waj 49
使用.on()为.live()已过时.
$(document).on("keypress", ".myText", function(e) {
if (e.which == 13) {
//do some stuff
}
});
Run Code Online (Sandbox Code Playgroud)
Sur*_*ran 21
做e.preventDefault()在的keyDown避免按钮的默认操作:
$('#myText').keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
}
alert(e.keyCode);
});
Run Code Online (Sandbox Code Playgroud)
the*_*dox 12
$(document).ready(function() {
$('#myText').keypress(function(e) {
if ( e.keyCode == 13 ) { // detect the enter key
$('#myButton').click(); // fire a sample click, you can do anything
}
});
$('#myButton').click(function(e) {
alert('Button click activated!');
});
});
Run Code Online (Sandbox Code Playgroud)
对于实时元素使用.on()如下:
$(document).ready(function() {
$(document).on('keypress', '#myText', function(e) {
if ( e.keyCode == 13 ) { // detect the enter key
$('#myButton').click(); // fire a sample click, you can do anything
}
});
$(document).on('click', '#myButton', function(e) {
alert('Button click activated!');
});
});
Run Code Online (Sandbox Code Playgroud)