【问题标题】:Unable to bind events in JQuery?无法在 JQuery 中绑定事件?
【发布时间】:2013-09-30 10:02:23
【问题描述】:

为什么在我的简单 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

【问题讨论】:

  • 该事件需要在 source 标签而不是 video 标签上完成,因此将其更改为:vid0.children().bind('ended', function() { 有效。

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


【解决方案1】:

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 事件不会冒泡到父元素,这意味着您的处理程序将永远不会被执行。

【讨论】:

  • .eq,它的复杂性与简单的数组访问相似吗?
  • @stackoverflowuser95 问题是你再次需要使用 jQuery 包装它
  • 重复我的问题,简单数组访问和.eq在计算复杂度和性能方面有什么不同吗?
【解决方案2】:

首先,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

【讨论】:

    【解决方案3】:

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

    这是一个有效的演示修复:http://jsfiddle.net/

    我在video 标签中添加了#video0#video1

    【讨论】:

      【解决方案4】:

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

      $(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();
          })
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 2010-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多