Jquery只在播放视频时才有效

时间:2017-03-28 15:48:22

标签: javascript jquery html

所以我有以下代码。我的目标是当我在第一个div中按下img时,它会在iframe中转换内部视频。当我点击关闭(glyphicon)时,它会回到原始状态。 这是有效的,问题是它只能运行一次。

如果有必要,我可以在代码段中创建一个版本。

另外,如果您知道更好的方法,请告诉我。 :)

由于

的index.html

<div class="col-md-6">
   <div class="squarediv"><img src="https://placeimg.com/400/400/any/1" data-img="https://placeimg.com/400/400/any/1" data-video="https://www.youtube.com/embed/72a27aLQ5B8">
   </div>

   <span class="glyphicon glyphicon-remove close" aria-hidden="true"></span>
</div>

scripts.js中

$('img').click(function () {
    video = '<iframe class="videop" src="' + $(this).attr('data-video') + '?modestbranding=1;autoplay=1;rel=0&amp;controls=0&amp;showinfo=0" width="1280" height="720" frameborder="0" allowfullscreen></iframe>';
    $(this).replaceWith(video);
    $(".squarediv").addClass("squarediv-active");
});

$('.close').click(function () {
    img = '<img src="' + $('.squarediv img').attr('data-img') + '" data-img="' + $('.squarediv img').attr('data-img') + '" data-video="' + $('.squarediv img').attr('data-video') + '" ></img>';
    $('.videop').replaceWith(img);
    $(".squarediv").removeClass("squarediv-active");
    $(".close").addClass("close-active");
});

1 个答案:

答案 0 :(得分:3)

问题是因为您使用replaceWith()。这意味着原始元素以及附加到它们的事件处理程序将被删除。

要解决此问题,请使用委托的事件处理程序,如下所示:

$('div.col-md-6').on('click', 'img', function () {
  // your code...
}).on('click', '.close', function() {
  // your code...
});

请注意,div.col-md-6主选择器可以更改为加载DOM中的任何公共父元素,我只使用它,因为它是您在问题中提供的示例HTML中唯一可用的内容。