jquery 准备好按键
jquery on ready keypressed
我的页面有加载了 ajax 的元素,我需要使用 enter 进入下一个输入、textarea 或 select。
一些输入具有格式化数字的功能,但上面的解决方案 运行 不止一次。
$(document).on('keypress',function(){
var inputs = $('input, select, textarea').on("keypress", function(e) {
if (e.which == 13) {
if ($(this).attr('data-format')) {
formatNumber($(this));
}
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
});
这对我有用
$(document).on('keypress',function(){
var inputs = $('input, select, textarea').one("keypress",function (e) {
if (e.which == 13) {
if($(this).attr('data-format')){
formatNumber($(this));
}
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
});
正如 Rory 和 Jason 提到的,您可能正在寻找事件委托。这将允许任何最初不存在的新输入在出现后仍然响应按键事件。这是一篇关于该主题的好文章:https://learn.jquery.com/events/event-delegation/,您的代码应如下所示:
更新:
$(document).on('keypress', 'input, select, textarea', function(e){
var inputs = $("input, select, textarea");
if (e.which == 13) {
if($(this).attr('data-format')){
formatNumber($(this));
}
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
我的页面有加载了 ajax 的元素,我需要使用 enter 进入下一个输入、textarea 或 select。 一些输入具有格式化数字的功能,但上面的解决方案 运行 不止一次。
$(document).on('keypress',function(){
var inputs = $('input, select, textarea').on("keypress", function(e) {
if (e.which == 13) {
if ($(this).attr('data-format')) {
formatNumber($(this));
}
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
});
这对我有用
$(document).on('keypress',function(){
var inputs = $('input, select, textarea').one("keypress",function (e) {
if (e.which == 13) {
if($(this).attr('data-format')){
formatNumber($(this));
}
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
});
正如 Rory 和 Jason 提到的,您可能正在寻找事件委托。这将允许任何最初不存在的新输入在出现后仍然响应按键事件。这是一篇关于该主题的好文章:https://learn.jquery.com/events/event-delegation/,您的代码应如下所示:
更新:
$(document).on('keypress', 'input, select, textarea', function(e){
var inputs = $("input, select, textarea");
if (e.which == 13) {
if($(this).attr('data-format')){
formatNumber($(this));
}
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});