事件监听器无法检测到视频的完成情况

时间:2017-03-27 11:18:15

标签: javascript jquery

我有一个html 5播放器,我试图检测视频何时结束。我试图用JQUERY和javascript检测它到目前为止没有运气。

<video id="myVideo"></video>

$("#myVideo").bind("ended", function () {
    alert('Video ended!');
});

var vid = document.getElementById("myVideo");
vid.src = "Content/Test.mp4";
vid.play();

vid.addEventListener('ended', videoFinish, false);

function videoFinish() {
    alert('Video ended!');
}   

3 个答案:

答案 0 :(得分:2)

它在JavaScript部分工作正常,但如果您更喜欢使用jQuery,则应该取消引用您打算使用JavaScript API进行视频方法和属性的任何jQuery对象。详细信息在Snippet中进行了评论。

BTW,.bind() jQuery method is deprecated, the .on() method is it's replacement.

<强>段

/*~~~~~~~~~~~~~~~~~ 
|| Plain JavaScript 
*/
// Creating <video>
var vid1 = document.createElement("video");

/* Assigning:
|| #id
|| src
|| controls
*/
vid1.id = 'vid1';
vid1.src = 'http://media6000.dropshots.com/photos/1381926/20170326/023642.mp4';
vid1.controls = true;

// Add node to DOM
document.body.appendChild(vid1);

// Register #vid1 to ended event to call videoFinish()
vid1.addEventListener('ended', videoFinish, false);

/*~~~~~~~
|| jQuery
*/
// Append this jQuery object to the DOM
$('<video id="vid2" src="http://media6000.dropshots.com/photos/1381926/20170326/023642.mp4" controls></video>').appendTo('body');

/* Dereference a jQuery object in order to use a 
|| method from a JavaScript API like HTML5 Video by
|| using bracket notation.
*/
var vid2 = $('#vid2')[0];

/* Now vid2 is a plain JavaScript object like vid1
|| Now it can easily use video methods and properties
*/
vid2.addEventListener('ended', videoFinish, false);

function videoFinish(e) {
  alert(e.target.id + ' has ended!');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

试试这个

 $('#myVideo').on('ended',function(){
          alert('Video ended!');
}

或者

<video src="video/endscene.mp4" id="myVideo" controls onended="videoEnded()">

答案 2 :(得分:1)

我怀疑这是因为您以编程方式添加了src或播放视频(但只是猜测,因为您没有回复我的问题)。尝试在视频加载后添加事件:

function onVideoLoaded(e) {
  console.log('onVideoLoaded', e.target === vid);
  vid.addEventListener('ended', onVideoEnded);
}

function onVideoEnded() {
  console.log('onVideoEnded');
}

vid.addEventListener('loadstart', onVideoLoaded);