将事件侦听器添加到多个 html5 视频以更新进度不起作用

Adding event listener to multiple html5 video to update progress not working

我正在制作一个视频页面,其中 html5 个视频将由 PHP 生成。每个都有一个唯一的 ID。每个都有自己的进度条。

我正在尝试使用 JQuery each 方法添加一个 eventListener updateProgress() 在视频播放时更新播放进度条。我已经用页面上的单个视频尝试了我的代码,它可以工作,但是当我在页面上有多个视频时,它就不会工作。希望你们能帮助我。谢谢!

$('video').each(function() {
    eid = this.id;
    this.addEventListener("timeUpdate"+eid, updateProgress(this, eid), false);
});

function updateProgress(vid, id) {
    var value = 0;
    if (vid.currentTime > 0) {
        value = (100 / vid.duration) * vid.currentTime;
    }

    $('#debug').html($('#debug').html()+'<br>'+'#vidProgress-'+id);
    $('#vidProgress-'+id).width(value + '%');
}

这是我的 JSFiddle link: https://jsfiddle.net/chris_poetfarmer/yoe30av2/8/

您需要传递函数引用,因为事件处理程序还需要将 eid 声明为局部变量

$('video').each(function () {
    var eid = this.id;
    this.addEventListener("timeupdate", function () {
        updateProgress(this, eid)
    }, false);
});

function updateProgress(vid, id) {
    var value = 0;
    if (vid.currentTime > 0) {
        value = (100 / vid.duration) * vid.currentTime;
    }

    $('#debug').html($('#debug').html() + '<br>' + '#vidProgress-' + id);
    $('#vidProgress-' + id).width(value + '%');
}

但可以简化为

$('video').on('timeupdate', updateProgress);

function updateProgress() {
    var value = 0,
        vid = this;
    if (vid.currentTime > 0) {
        value = (100 / vid.duration) * vid.currentTime;
    }

    $('#debug').html($('#debug').html() + '<br>' + '#vidProgress-' + vid.id);
    $('#vidProgress-'+this.id).width(value + '%');
}