2011-02-04 3 views
3

:あなたがダイアログを閉じた後、ダイアログを再度開く場合jQueryホットキー - バインドを解除しますか?私は次のようにホットキーを初期化するjQueryのダイアログを持って

<script type="text/javascript"> 
    $(document).bind('keydown', '<%=(i+1)%>',function (evt) { 
    // do stuff 
    }); 
</script> 

は、これは1-9をループ...

問題は、あります。それは再バインディングを維持するので、あなたが '1'のキーダウンをすると、それは2回、3回、4回など実行されます。

私は

$(document).unbind('keydown', '1'); 
$(document).unbind('keydown', '2'); 
$(document).unbind('keydown', '3'); 
$(document).unbind('keydown', '4'); 
$(document).unbind('keydown', '5'); 
$(document).unbind('keydown', '6'); 
$(document).unbind('keydown', '7'); 
$(document).unbind('keydown', '8'); 
$(document).unbind('keydown', '9'); 

との対話密接にキーバインドを殺害しようとしたしかし、それは効果がなかったです。どのようにこれを処理するための任意のアイデアですか?

おかげ

+0

あなたは 'http://api.jquery.com/die/)(' .dieを試してみました – Rafay

答えて

3

.unbind()は、eventData引数をサポートしていないことに注意してください。これが、バインド解除が機能しない理由です。

私の頭の上には、2つの異なるアプローチがあります。これらは唯一のドキュメントレベルのKeyDown束縛されている場合は、次のことができ、「完全な」次のようにバインド解除へ:

$(document).unbind('keydown'); // unbinds *all* keydown handers on the document 

を別の方法として、あなたは非匿名関数として、あなたのKeyDownハンドラを保存して渡すように周りの参照を保持することができますダイアログを閉じるときにバックのアンバインドします

function onkeydown(evt) { 
    // do stuff 
} 

$(document).bind('keydown', '<%=(i+1)%>', onkeydown); 

// later, in the dialog's "shutdown" code: 
$(document).unbind('keydown', onkeydown); 

私は、同じ機能がしかし、複数回バインドされたときに、これがどのように機能するか100%正ではありませんよ。 eventDataを削除し、イベントハンドラ内でevent.whichを使用して、どのキーが押されたかを判断するほうが良いでしょう(ハンドラが一度だけバインドされる必要があります)。

0

あなたは、このメソッドは、イベントに文書がロードされた1時間を結合し

<script type="text/javascript"> 
$(document).ready(function() { 
    $(document).bind('keydown', '<%=(i+1)%>',function (evt) { 
     // do stuff 
    }); 
}); 
</script> 

を使用することができます。

1

私は

注)1(と組み合わせてのKeyDownイベントの名前空間を使用して「keydown.g」で.Gを、同様の問題を解決しました。それは別のスコープに入れられます。これを後で文書のすべてのkeydownをバインド解除せずにバインド解除できます。

$(document).one("keydown.g", function(e) { 
// tab key 
if (e.which == "9") { 
    e.preventDefault(); 
    // do something like focus on a field 
    $("#target").focus(); 
    // once you've moved the focus, you can unbind and go back to tabbing normally 
    $(document).unbind("keydown.g"); 
} 
}); 

< 3のjQuery

関連する問題