点击缩略图嵌入YouTube视频遇VidContainer null错误的解决方法
问题
我有一个带视频缩略图的主页,需求是点击缩略图时,在新窗口的一半区域打开对应的YouTube视频。但用JavaScript实现时,JS脚本第46行出现“VidContainer is null”错误。相关代码如下:
主页HTML
<html> <head> <title>YouTube API</title> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css"> </head> <body> <div class="header"> <br> <h1>YouTube API Search</h1> <div class="search-bar"> <input type="text" id="search" placeholder="Search for videos"> <input type = "image" src = "search.png" id = "search-button"></button> </div> <div id="keywordPopup" class="popup" style="display: none;"> <br> <input type="text" id="customKeyword" placeholder="Enter custom keyword"> <button id="submitKeyword">Submit</button> <button id="cancelKeyword">Cancel</button> </div> <div class = "addKeyword"> <button id="addKeywordButton" class="add-button">+</button> </div> <div class="category-buttons"> <button class="category-button" data-category="Software Quality Assurance">Software Quality Assurance</button> <button class="category-button" data-category="Computing">Computing</button> </div> </div> <div class = "content"> <br> <div class="row"> <div class="col-md-12"> <div id="videos"></div> </div> </div> </div> <div id="loading" style="display: none"> <p>Loading...</p> </div> <div id="error" style="display:none"> <p>An error occurred while fetching videos.</p> </div> <div id="videoScreen" class="screen"> <div class="screen-content"> <span class="close" onclick="closeVideo()">×</span> <iframe id="videoFrame" width="560" height="315" src="" frameborder="0" allowfullscreen></iframe> <div id="fb-root"></div> <script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v18.0" nonce="wykFjTT7"></script> <input type = "image" style="width:60px;height:60px;" src = "save.png" onclick = "openNW()" id = "download"></button> <input type="image" style="width:60px;height:60px;" src = "2023_Facebook_icon.png" onclick="location.href='https://www.facebook.com/sharer/sharer.php?u=example.org';" id = "fb-share" /></button> <a class="twitter-share-button" href="https://twitter.com/intent/tweet?text=Hello%20world"><img src="X.png" width="60px" height="60px"></a> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script src="ytsearch.js"></script> </body> </html>
新窗口HTML(file.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Embedded YouTube Video</title> </head> <body> <div id="vid-container"> <div id="player"></div> </div> <script src="https://www.youtube.com/iframe_api"></script> <script src = "ytsearch.js"></script> </body> </html>
JS脚本(ytsearch.js相关部分)
function videoSearch(key, search, maxResults, videoDuration) { $("#videos").empty(); $.get("https://www.googleapis.com/youtube/v3/search?key=" + key + "&type=video&part=snippet&maxResults=" + maxResults + "&q=" + search + "&videoDuration=" + videoDuration, function(data){ var videosContainer = $("<div class='row'></div>"); console.log(data); data.items.forEach(function (item, index) { var videoColumn = $("<div class='col-md-4'></div>"); var videoContainer = $("<div class='video-container'></div>"); // 创建视频缩略图并绑定点击事件 var thumbnail = $("<img src='" + item.snippet.thumbnails.medium.url + "' alt='Video Thumbnail'>"); thumbnail.on("click", function () { var vidContainer = document.getElementById("vid-container"); vidContainer.player.innerHTML = `<iframe src = "https://www.youtube.com/embed/" + item.id.videoId frameborder = "0" allowfullscreen></iframe>` window.open("file.html"); });
解决方案
错误原因
- DOM元素不存在:
vid-container是新窗口file.html独有的元素,主页DOM中根本没有这个节点,所以document.getElementById("vid-container")必然返回null。 - 逻辑顺序颠倒:代码先尝试修改不存在的元素,再打开新窗口,完全搞反了执行顺序。
修复步骤
1. 修改主页的缩略图点击事件逻辑
删掉原来操作新窗口DOM的错误代码,改为打开新窗口时通过URL参数传递视频ID:
thumbnail.on("click", function () { // 传递视频ID到新窗口,同时设置新窗口初始大小 window.open(`file.html?v=${item.id.videoId}`, "_blank", "width=1000,height=800"); });
2. 修改新窗口HTML,添加样式实现“一半区域”显示
在file.html的<head>中添加CSS,让视频容器占窗口宽度的50%:
<head> <meta charset="UTF-8"> <title>Embedded YouTube Video</title> <style> body { margin: 0; padding: 20px; box-sizing: border-box; } #vid-container { width: 50%; height: 90vh; } #player iframe { width: 100%; height: 100%; border: none; } </style> </head>
3. 在ytsearch.js中添加新窗口的视频加载逻辑
添加监听新窗口加载的代码,解析URL参数中的视频ID并渲染播放器:
// 监听新窗口加载完成事件 window.addEventListener('load', function() { // 解析URL参数获取视频ID const urlParams = new URLSearchParams(window.location.search); const videoId = urlParams.get('v'); if (videoId) { const playerDiv = document.getElementById('player'); // 嵌入YouTube视频iframe playerDiv.innerHTML = `<iframe src="https://www.youtube.com/embed/${videoId}" allowfullscreen></iframe>`; // 可选:用YouTube官方API创建播放器 // function onYouTubeIframeAPIReady() { // new YT.Player('player', { // height: '100%', // width: '100%', // videoId: videoId, // playerVars: { 'playsinline': 1 } // }); // } } });
验证效果
点击主页的视频缩略图后,会打开新窗口,视频会在窗口的50%宽度区域内正常显示,同时不会再出现“VidContainer is null”的错误。
内容的提问来源于stack exchange,提问作者not_castillo
相关产品推荐
相关产品推荐

