jquery on ready keypressed

时间:2015-09-25 15:25:21

标签: jquery ajax keypress

我的页面有用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();
        }
    }
});
});

2 个答案:

答案 0 :(得分:0)

这对我有用

$(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();
    }
  }
});

});

答案 1 :(得分:0)

正如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();
    }
  }
});