2011-08-12 15 views
1

私は以下の機能をクリックすると起動しますが、新しい機能を作成せずに入力するとどのように起動するのでしょうか? (可能なら)。クリックとキープの両方で同じ機能をトリガーする

$("#jump_menu select option").click(function(){ 
    var hash = $(this).val(); 
    var target_offset = $(hash).offset(); 
    $('html, body').animate({scrollTop:target_offset.top}, 500); 
}) 

答えて

4

ではなく...

$("#jump_menu select").change 

への結合を試してみてください。

またはちょうどあなたが必要なものに、スタンドアロン機能、バインドに移動:

function handler(elem) { 
    var hash = $(elem).val(); 
    var target_offset = $(hash).offset(); 
    $('html, body').animate({scrollTop:target_offset.top}, 500); 
} 

$('#jump_menu select option').click(handler); 
$('#jump_menu select').change(handler); 

あなたが単一選択のために二回あなたのハンドラを呼び出すことはありません確実にするためにかかわらず、あなたはイベントのタイムスタンプを保存して比較する必要があるかもしれません。あなたは、むしろそうのようなあなたの.click機能でそれを宣言するよりも、あなたの関数を宣言グローバルに持って

+0

唯一の問題は、誰かが上にスクロールして前のオプションを再選択しようとしたときに、再び発火しないようにすることです。 –

+0

@George:その場合は、コードをスタンドアロンの名前付き関数で無名関数に入れ、処理したいイベントにバインドするだけです。 – sje397

+0

@George:Edited。 – sje397

0
function runAnimate() { 
    var hash = $(this).val(); 
    var target_offset = $(hash).offset(); 
    $('html, body').animate({scrollTop:target_offset.top}, 500); 
} 

$("#jump_menu select option").click(runAnimate); 

$('body').change(runAnimate); 
+0

申し訳ありません:$( "#jump_menu select")。change(runAnimate);代わりに最後のコードブロック – defuz

+0

ありがとうが、私はEnterキーを押しても何も起こりません。 –

1

:その後

function animateBody() { 
    var hash = $(this).val(); 
    var target_offset = $(hash).offset(); 
    $('html, body').animate({scrollTop:target_offset.top}, 500); 
} 

、あなたはそれを2回再宣言することなく、複数のイベントに関数をバインドすることができます。

//Other JQuery/Javascript 

function animateBody() { 
    var hash = $(this).val(); 
    var target_offset = $(hash).offset(); 
    $('html, body').animate({scrollTop:target_offset.top}, 500); 
} 

$("#jump_menu select option").click(animateBody); 
$("#jump_menu select").change(animateBody); 

//Other JQuery/Javascript 

$("#jump_menu select option").click(animateBody); 
$("#jump_menu select").change(animateBody); 

結果として生じるが、このようなものを見ることができます

幸運を祈る!

0
$(selector).on('keyup , change' ,function() { 
--- Do some thing --- 
}); 
関連する問題