【发布时间】:2021-03-08 13:09:27
【问题描述】:
我是 CS 新手,目前正在从事个人项目。我正在创建一个网络应用程序,用户可以在其中将 YouTube URL 复制并粘贴到搜索框中的视频,然后能够在单击观看后在同一网页上观看视频。为了获取视频 ID,我使用了正则表达式:
function getId(url) {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
const match = url.match(regExp);
return (match && match[2].length === 11)
? match[2]
: null;
}
这就是我获取用户输入的方式:
var inputVal = document.getElementById("userInput").value;
为了获取视频 ID,我在用户的inputVal 上拨打了getId:
var newVideoId = getId(inputVal)
以下是用于在我的页面上播放视频的 YouTube API。但是,我发现很难将newVideoId 变量传递给player 对象下的API。
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'newVideoId', //the problem lies here
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
}
问题是,单击按钮后,我的屏幕上没有显示任何内容。我可以console.log这个ID;这意味着我从正则表达式中得到了正确的 ID。
对于如何在 API 中使用从用户处获得的动态 ID 的任何帮助,我将不胜感激!谢谢
【问题讨论】:
-
videoId: newVideoId(去掉引号,你有文本,不是变量) -
谢谢。我试过了,但没用!
-
“没有工作”作为问题描述不是很有帮助:) 如果加载 Youtube 播放器的代码在用户填写表单之前运行,这显然不起作用,因为
newVideoId还不存在。
标签: javascript youtube-api youtube-iframe-api