无法在JQuery中绑定事件?

时间:2013-09-30 10:02:24

标签: javascript jquery events javascript-events html5-video

为什么我的简单JQuery代码中没有绑定事件? - http://pastebin.com/24J6q5G0

相关部分:

<div class="videoWrapper">
    <video controls preload autoplay>
        <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
        <source src="http://techslides.com/demos/sample-videos/small.ogv" type="video/ogg">
    </video>
</div>

<div class="videoWrapper">
    <video controls preload="none">
        <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
        <source src="http://techslides.com/demos/sample-videos/small.ogv" type="video/ogg">
    </video>
</div>

和javascript:

$(document).ready(function() {
    var vid0 = $(document.getElementsByClassName('videoWrapper')[0]);
    var vid1 = $(document.getElementsByClassName('videoWrapper')[1]);
    vid1.hide();
    vid0.bind('ended', function() {
        vid1.show();
    })
})

(我一直关注Detect when an HTML5 video finishes

4 个答案:

答案 0 :(得分:2)

ended event未传播(冒泡),请尝试

$(document).ready(function() {
    var wrappers = $('.videoWrapper');
    wrappers.eq(1).hide()
    wrappers.eq(0).find('video').bind('ended', function() {
        wrappers.eq(1).show();
    })
})

在您的情况下,您将事件绑定到包装div元素,但ended事件未冒泡到父元素,这意味着您的处理程序永远不会被执行。

答案 1 :(得分:0)

首先,HTML5视频的事件在video元素上触发,因此您附加了错误的元素。另外,你创建jQuery选择器的方法有点奇怪。试试这个:

var $vid0 = $('.videoWrapper video').eq(0);
var $vid1 = $('.videoWrapper video').eq(1);
$vid1.parent().hide();
$vid0.bind('ended', function() {
    $vid1.parent().show();
})

Example fiddle

答案 2 :(得分:-1)

它不起作用的原因是因为你的vid0是包装器div而ended事件需要video标签。

以下是一个有效的演示修补程序:http://jsfiddle.net/

我将#video0#video1添加到video代码。

答案 3 :(得分:-1)

我使用的解决方案(认为当时只有一个[错误的]答案)是:

$(document).ready(function() {
    var vid0 = $(document.getElementsByClassName('videoWrapper')[0]);
    var vid1 = $(document.getElementsByClassName('videoWrapper')[1]);
    vid1.hide();
    vid0.children().bind('ended', function() {    // Note this line
        vid1.show();
    })
})