3

Enterキーが押されたときに処理するために、常に次のコードを記述します。

$("#selectorid").keypress(function (e) {
    if (e.keyCode == 13) {
        var targetType = e.originalTarget
            ? e.originalTarget.type.toLowerCase()
            : e.srcElement.tagName.toLowerCase();
        if (targetType != "textarea") {
            e.preventDefault();
            e.stopPropagation();
            // code to handler enter key pressed
        }
    }
});

私が書くことができるようにjQueryを拡張する方法はありますか:

$("#selectorid").enterKeyPress(fn);
4

4 に答える 4

5

jquery を次のように拡張できます。

jQuery.fn.returnPress = function(x) {
  return this.each(function() {
    jQuery(this).keypress(function(e) {
      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        x();
        return false;
      }
      else {
        return true;
      }
    });
  });
};

次のように呼び出すことができます:

$('selector').returnPress(function() { alert('enter pressed'); });
于 2010-03-26T17:50:44.330 に答える
4

David G の言うことを実行できますが、おそらくこれにアプローチする最も正しい方法は、カスタム イベントを作成することです。

$(document).keypress(function(evt){
    if(evt.keyCode==13) $(evt.target).trigger('enterPress');
});

次のようにバインドできます。

$(document).bind('enterPress', fn);

ここで例を参照してください: http://jquery.nodnod.net/cases/1821/run

The advantage to this approach is that you can bind, unbind, namespace, and trigger the event like any other event in jQuery.

于 2010-03-26T18:06:42.670 に答える
2

次のように、少し少ないコードでプラグインとして定義できます。

jQuery.fn.enterKeyPress = function(callback) {
  return this.not("textarea").keypress(function (e) {
    if (e.keyCode == 13) {
      callback($(this));
      return false;
    }
  });
};

次のように使用します。

$("input").enterKeyPress(function() { alert('hi'); });

このアプローチでも は無視さ<textarea>れますが、すべてのキーストロークをチェックする代わりに、keypressイベントをテキストエリアにバインドすることはありません。

于 2010-03-26T17:52:40.087 に答える
0

これは、フォーム要素の Enter キーをキャプチャしてタブに変換するために使用するものです。Enterキーがテキストエリア、送信、リセット、ボタン要素で正常に機能するようにしました。

$.fn.focusNext = function(e) {
  var t = $(this);
  if ( t.is(":submit")==true || t.is(":reset")==true || t.is("textarea")==true || t.is("button")==true ) { exit(); }

  if (e.which==13 || e.which==3) {
    return this.each(function() {
      e.preventDefault();
      var fields = $(this).parents("form:eq(0)").find(":input:visible");
      var index = fields.index( this );
      if ( index > -1 && ( index + 1 ) < fields.length ) { fields.eq( index + 1 ).focus(); }
    });
  }
  return true;
};

そして、それを使用するには、そのように呼ばれます

$(":input").keypress(function(e) { $(this).focusNext(e); });

また

$(":input").live("keypress", function(e) { $(this).focusNext(e); });
于 2010-07-31T00:18:46.420 に答える