我有以下代码设置,可以在变量搜索栏上使用“更改”和“输入”事件监听器。正如您所看到的,它们是完全重复的,所以我想知道如何将 2 个事件监听器合并到一个函数中?
// 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;
});
最佳答案
将回调函数定义为命名函数并给出引用而不是重复。
function seek() {
var time = video.duration * (seekBar.value / 100);
video.currentTime = time;
}
seekBar.addEventListener("change", seek);
seekBar.addEventListener("input", seek);
或者做这样的事情:
['change', 'input'].forEach(function(event){
seekBar.addEventListener(event, seek);
});
在 jQuery 中,您可以使用 on()
用空格分隔多个事件的方法。
$(seekBar).on('input change', function() {
var time = video.duration * (seekBar.value / 100);
video.currentTime = time;
})
关于jquery - 多个事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47598202/