我正在使用html、css和javascript制作一个静态的组合网站。index.html
我有一个图片库。每张图片代表一部影片。当点击一个图片时,用户会被引导至 detail.html
页面,其中某个视频应该和引用数据一起在iframe中显示。然而,我正在努力让视频加载到这个页面中。detail.html
中的图片时,点击页面上的 index.html
页面。它加载了页面,但没有视频.这里是html代码的 index.html
:
<a href="#" onclick="myFunction()">
<img alt="picture" src="img/portfolio/filmcity.jpg" width="100%" />
</a>
这是Javascript。
function myFunction() {
window.location = 'detail.html';
var video = document.getElementById("myFrame");
video.setAttribute("src", "https://www.youtube.com/embed/Jiu42WJ9Vdk");
}
这是html代码 detail.html
:
<iframe width="100%" id="myFrame" height="60%" src="">
</iframe>
谁能帮帮我?
对于你所有的链接到detail.html有这样的URL。detail.html?video_id=XXXXX
其中XXXX是你想链接到的youtube id。
<a href="detail.html?video_id=Jiu42WJ9Vdk"> Watch video </a>
详细.HTML
<iframe width="100%" id="myFrame" height="60%" src="about:blank;"></iframe>
JAVASCRIPT:
function _get(name) {
url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return "";
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var _youtube_id = _get("video_id");
if (_youtube_id.match(/^[0-9a-z]+$/)){
var video = document.getElementById("myFrame");
video.setAttribute("src", "https://www.youtube.com/embed/" + _youtube_id);
}
你不能在旧页面上运行一个函数的同时导航到一个新页面 You can't navigate to a new page while still running a function on the old page. 这不是JavaScript的工作方式。你需要在页面加载时在它运行的页面上调用你的函数。也许像这样。
在index.html上
<!-- include the video ID as a URL parameter -->
<a href="detail.html?vid=Jiu42WJ9Vdk"> ... </a>
关于 detail.html
<iframe width="100%" id="myFrame" height="60%" src=""></iframe>
<script>
// get the video ID from the URL and use it in the iframe source string
let url = new URL(window.location.href);
let vid = url.searchParams.get("vid");
let videoEl = document.getElementById("myFrame");
video.setAttribute("src", "https://www.youtube.com/embed/" + vid);
</script>