简体   繁体   English

接收来自多个HTML5视频的事件

[英]Receive events from multiple HTML5 videos

I have multiple videos and want to get an event from all of them. 我有多个视频,希望从所有视频中获得一个活动。 But I get only the event from one of them (tested in Chrome). 但是我只能从其中一个获得事件(在Chrome中测试)。 Why? 为什么?

HTML: HTML:

<video id="video1" preload="auto" src="video1.ogg"></video>
<video id="video2" preload="auto" src="video2.ogg"></video>

JS: JS:

$('video').on('canplay', function(){
    console.log($(this).attr('id'));
});

jsFiddle jsFiddle

EDIT: 编辑:

Ok.. it is really strange. 好吧..真的很奇怪。 On the very first load I get sometimes both events. 在第一次加载时,有时会遇到两个事件。 But after that on every reload I get just an event from one of them!? 但是在每次重新加载之后,我都会从其中一个事件中得到一个事件! Here a screenshot of my console: 这是我的控制台的屏幕截图:

在此处输入图片说明

The problem is that the 'canplay' event has already fired by the time you register it. 问题在于,在您注册时“ canplay”事件已经触发。 I believe this is because jsFiddle wraps your code inside of $(window).load(... . If you were to move the script into the html, like on this example , it should work. 我相信这是因为jsFiddle将您的代码包装在$(window).load(... ,如果要将脚本移动到html中,例如在此示例中 ,它应该可以工作。

Most of the time, if you know for sure that your script is going to run synchronously right after the video element is created with a src , you can assume that none of those events have been fired. 在大多数情况下,如果您确定在使用src创建video元素后脚本将立即同步运行,则可以假定没有触发任何事件。 But, just to be safe, and especially when you don't know how your code will be used, I recommend something like this: 但是,为了安全起见,尤其是当您不知道如何使用代码时,我建议使用类似以下内容的代码:

function handleCanplay(video) {
    console.log($(video).attr('id'));
};

$('video').each(function () {
    //first, check if we missed the 'canplay' event
    if (this.readyState >= this.HAVE_FUTURE_DATA) {
        //yup, we missed it, so run this immediately.
        handleCanplay(this);
    } else {
        //no, we didn't miss it, so listen for it
        $(this).on('canplay', function () {
            handleCanplay(this);
        });
    }
});

Working example here . 这里的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM