javascript - 在 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);
}
}
});
}
解决方案
在向该节点添加新元素之前,请从节点中删除子元素
const currentDiv = document.getElementById("cnn");
currentDiv.innerHTML = "";
currentDiv.appendChild(brr);
推荐阅读
- javascript - 尝试使用 2 个参数创建命令
- mysql - MYSQL 我应该使用内连接来提取 Max Date 上的数据吗
- reactjs - 在 AWS 放大部署中公开的 React 源代码
- c# - INotifyPropertyChanged 用于位于 DLL 文件中的属性
- python - 文本 Python 循环
- python - 如何用连字符检查句子中的多个单词
- excel-addins - 用于自定义功能区选项卡的 Excel 加载项以包含来自 MSIP.ExcelAddin 的控件
- django - 更新 Django 中的大量外键引用
- authorization - 获取要分配给单个课程的令牌。- SAS 代币
- node.js - 将表单数据分配给 node.js 中的 postgres 池