2017-12-01 14 views
2

変数シークバーで 'change'と 'input'イベントリスナーの両方を使用するように、以下のコードをセットアップしました。ご覧のとおり、これらは重複しているので、2つのイベントリスナーを1つの関数にマージする方法が不思議です。複数のイベントリスナー?

// Event listener for the seek bar 
seekBar.addEventListener("change", function() { 
    // Calculate the new time 
    var time = video.duration * (seekBar.value/100); 

    // Update the video time 
    video.currentTime = time; 
}); 

// Event listener for the seek bar 
seekBar.addEventListener("input", function() { 
    // Calculate the new time 
    var time = video.duration * (seekBar.value/100); 

    // Update the video time 
    video.currentTime = time; 
}); 
+0

[同じ関数にバインド複数のイベント]の可能な重複(https://stackoverflow.com/questions/17425311/bind-multiple-events-to-same-function) –

答えて

3

コールバック関数を名前付き関数として定義し、複製する代わりに参照を与えます。

function seek() { 
    var time = video.duration * (seekBar.value/100); 
    video.currentTime = time; 
} 

seekBar.addEventListener("change", seek); 
seekBar.addEventListener("input", seek); 

またはこのような何か:あなたはスペースでon()メソッドを使用することができますjQueryので

['change', 'input'].forEach(function(event){ 
    seekBar.addEventListener(event, seek); 
}); 

複数のイベントを分離します。

$(seekBar).on('input change', function() { 
    var time = video.duration * (seekBar.value/100); 
    video.currentTime = time; 
}) 
関連する問題