【发布时间】:2022-01-04 13:33:44
【问题描述】:
因为我想摆脱JQuery,我开始用Javascript重写我的代码。
我有一个 Bootstrap 5 模态,当我关闭模态时,JQuery 代码会关闭 Youtube 视频。这是必要的,因为如果没有它,您可能会听到视频中的音频,从而破坏用户体验。
但是,我编写的 JS 代码的工作方式不一样,我不知道为什么。 当我关闭并重新打开 Modal 时,Youtube 视频不再可用。
JQuery 代码:
$(document).ready(function () {
/* YOUTUBE TURNS OFF IF I CLICK CLOSE*/
var url = $("#Youtube").attr('src');
$("#VideoModal").on('hide.bs.modal', function () {
$("#Youtube").attr('src', '');
});
$("VideoModal").on('show.bs.modal', function () {
$("#YoutubeVideo").attr('src', url);
});
});
我的Vanilla Javascript代码:
document.addEventListener('DOMContentLoaded', (event) => {
var YoutubeVideo= document.getElementById('YoutubeVideo');
var VideoModal = document.getElementById('VideoModal');
YoutubeVideo.getAttribute('src');
VideoModal.addEventListener('hide.bs.modal', function() {
YoutubeDocFilerApproval.removeAttribute('src');
})
VideoModal.addEventListener('show.bs.modal', function() {
YoutubeVideo.setAttribute('src', url);
})
HTML 代码
<div class="modal fade " id="VideoModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg " role="document" style="box-sizing: content-box; ">
<div class="modal-content" style="padding: 0px; border:none;">
<div class="modal-header bg-dark ">
<h5 class="modal-title" id="exampleModalLabel">Title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="background-color: white">
</button>
</div>
<div class="modal-body bg-dark">
<iframe id="YoutubeVideo" width="560" height="315" src="https://www.youtube.com/embed/hTihS7vDeik" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<div class="modal-footer bg-dark">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
我做错了什么?
PS.:因为我是 Stackoverflow 的新手,如果我的问题不清楚或有任何问题,请告诉我。这将帮助我提高提问技巧。
编辑:变量名已更改,以使代码更易于阅读。
【问题讨论】:
-
您在线传递了错误的 ID:
var DocfilerApprovalVideoModal = document.getElementById('ebp_YoutubeDocFilerApproval');- 它应该是ebp_DocfilerApprovalVideoModal而不是ebp_YoutubeDocFilerApproval。 -
谢谢。已更正。
-
你也忘了初始化
url变量:YoutubeDocFilerApproval.getAttribute('src');应该是var url = YoutubeDocFilerApproval.getAttribute('src');
标签: javascript jquery bootstrap-modal bootstrap-5