首页 > 解决方案 > 在 DOM 中动态创建视频会导致重复

问题描述

我是 JS 新手,我正在尝试创建动态网站并从中学习。但是我很挣扎,因为我尝试了多个代码和试验,但我总是有重复的视频。

这是 HTML:

<div class="container" id="cnn">
        

</div>

这是JS代码:

function enter() {
 var video = document.createElement("video");
 video.type = "video/mp4";
 video.src = "../images/myMovie.mp4";
 video.autoplay = true;
 video.muted = true;
 video.id = "vdd"
 document.body.appendChild(video);

 var step2 = false;


video.addEventListener("timeupdate", function(){

// current time is given in seconds
if(this.currentTime >= 1) {
    // pause the playback
    this.pause();
    this.remove();
    step2 = true;
    if (step2 == true){
      document.getElementById("cnn").style.display = "inline"
      console.log("Test 1");
    
      const x = document.createElement("video");
      const brr = document.createElement("div");
    
      x.type = "video/mkv";
      x.src = "../images/space.mkv";
      x.autoplay = true;
      x.muted = true;
      x.id = "vdd1"
      
     brr.appendChild(x);
    
    // add the newly created element and its content into the DOM
    const currentDiv = document.getElementById("cnn");
    currentDiv.appendChild(brr);
    
    }
    
 }

});

}

标签: javascriptapidomdynamic

解决方案


在向该节点添加新元素之前,请从节点中删除子元素

const currentDiv = document.getElementById("cnn");
currentDiv.innerHTML = "";
currentDiv.appendChild(brr);

推荐阅读