Iframe追加创建一个副本

iframe appends to makes a copy

本文关键字:一个 副本 追加 创建 Iframe      更新时间:2023-09-26

我有这个jQuery代码,但当我试图执行它,它使blok2的副本,当它返回到其正式状态。有人知道怎么解决这个问题吗?

每当我点击我的块它就会扩展并像它应该的那样显示视频。但是当我点击缩放它时,它会复制iframe,它不会隐藏。我尝试了一些解决方案,但我不知道如何取消隐藏iframe,它不会翻倍。

$(document).ready(function() {
  $(".blok2").click(function() {
    $(".codeacademy").toggle();
  });
  $(".blok2").click(function() {
    $("<iframe />", {
      src: "https://www.youtube.com/embed/07Q6aUPfqkM"
    }).appendTo(".blok2");
  });
});
.rij1 {
  display: flex;
  width: 500px;
}
.rij2 {
  display: flex;
  width: 500px;
}
.blok1 {
  background-color: cadetblue;
  height: 250px;
  width: 250px;
}
.blok2 {
  background-color: palevioletred;
  height: 250px;
  width: 250px;
}
.blok3 {
  background-color: darkseagreen;
  height: 250px;
  width: 250px;
}
.blok4 {
  background-color: coral;
  height: 250px;
  width: 250px;
}
img.codeacademy {
  display: block;
  width: 100%;
  height: auto;
  content: url("http://s3.amazonaws.com/codecademy-blog/assets/logo_blue_dark.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='rij1'>
  <div class='blok1'></div>
  <div class='blok2'>
    <img class="codeacademy">
  </div>
</div>
<div class='rij2'>
  <div class='blok3'></div>
  <div class='blok4'></div>
</div>

问题是由于您有两个点击事件处理程序附加到blok2元素的事实-它们都在每次点击时执行;它们不会像你期望的那样在连续点击时切换。

要解决这个问题,你可以有一个单一的点击事件处理程序,检查是否有iframeblok2元素已经。如果有,它会删除它并显示codecademy图像。如果不是,它将创建iframe并隐藏图像。像这样:

$(document).ready(function() {
  $(".blok2").click(function() {
    var $iframe = $(this).find('iframe');
    if ($iframe.length) {
      $(".codeacademy").show();
      $iframe.remove();
    } else {
      $(".codeacademy").hide();
      $("<iframe />", {
        src: "https://www.youtube.com/embed/07Q6aUPfqkM"
      }).appendTo(".blok2");
    }
  });
});
.rij1 {
  display: flex;
  width: 500px;
}
.rij2 {
  display: flex;
  width: 500px;
}
.blok1 {
  background-color: cadetblue;
  height: 250px;
  width: 250px;
}
.blok2 {
  background-color: palevioletred;
  height: 250px;
  width: 250px;
}
.blok3 {
  background-color: darkseagreen;
  height: 250px;
  width: 250px;
}
.blok4 {
  background-color: coral;
  height: 250px;
  width: 250px;
}
img.codeacademy {
  display: block;
  width: 100%;
  height: auto;
  content: url("http://s3.amazonaws.com/codecademy-blog/assets/logo_blue_dark.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='rij1'>
  <div class='blok1'></div>
  <div class='blok2'>
    <img class="codeacademy">
  </div>
</div>
<div class='rij2'>
  <div class='blok3'></div>
  <div class='blok4'></div>
</div>