2010-11-28 19 views

答えて

10

現代のjQuery(1.7とアップ)イベントハンドラをバインドする.on()を使用:のjQueryの

// delegate binding - replaces .live() and .delegate() 
$(document.body).on("keyup", ":input", function(e) { 
    if(e.which == 13) 
    $(this).trigger("enter"); 
}); 

// direct binding - analogous to .keyup() 
$(":input").on("keyup", function(e) { 
    if(e.which == 13) 
    $(this).trigger("enter"); 
}); 

以前のバージョンは、以下のいずれかの方法を使用します。すべての要素に対して単一の.live()または.delegate()イベントハンドラを持つことができます。

$("selector").bind("enter", function(){ 
    //enter was pressed! 
}); 

You can test it out here:あなたが持っている正確に何をする可能性のある:input要素について

$(document.body).delegate(":input", "keyup", function(e) { 
    if(e.which == 13) 
    $(this).trigger("enter"); 
}); 

ない:次に、このように、あなたのカスタムイベントをトリガするためにそれを使用。

+0

ありがとう!また、初めてjsfiddle.comについて聞きました。とても便利。 – Ovesh

4
$("selector").keyup(function (e) { 
    if (e.keyCode == 13) { 
    $(this).trigger("enter"); 
    } 
}).bind("enter", function() { 
    // event code here 
}); 

偶然にカスタムイベントを使用する他のjQueryコードと衝突の可能性を減らすために、名前空間イベント名を使用することをお勧めします。したがって、"enter"の代わりに、"enter.mywebapp"またはこれに類するものを使用できます。これにより、より多くのカスタムイベントを使用することができます。

+0

namespaces come * after *イベント名。 '" enter.mywebapp "' :) –

+0

@ニック:固定、ありがとう。 – Tomalak

関連する問題