我正在尝试使用一些JS在页面上渲染多个Youtube视频。带有类youtubevid的第一个div将被呈现并转换为iframe。其余的视频不会呈现。就像循环在第一个div之后停止一样。有人知道为什么会这样吗?这是JFIDDle链接(https://jsfiddle.net/zondhe8j/21/)
这是HTML
<div id="K1QICrgxTjA" data-step="1" class="youtubeVid" videosrc="https://www.youtube.com/watch?v=K1QICrgxTjA" videoid="K1QICrgxTjA"></div>
<div id="K1QICrgxTjA" data-step="1" class="youtubeVid" videosrc="https://www.youtube.com/watch?v=K1QICrgxTjA" videoid="K1QICrgxTjA"></div>
<div id="K1QICrgxTjA" data-step="1" class="youtubeVid" videosrc="https://www.youtube.com/watch?v=K1QICrgxTjA" videoid="K1QICrgxTjA"></div>
<div id="K1QICrgxTjA" data-step="1" class="youtubeVid" videosrc="https://www.youtube.com/watch?v=K1QICrgxTjA" videoid="K1QICrgxTjA"></div>
这是JS
var hasVideo = document.getElementsByClassName('youtubeVid').length > 0;
if (hasVideo){
var players = [];
document.querySelectorAll('.youtubeVid').forEach(youtubeSection => {
var vidID = youtubeSection.getAttribute('videoID');
var title = youtubeSection.getAttribute('title');
var type = youtubeSection.getAttribute('type');
var playerName = youtubeSection.getAttribute('id');
if (youtubeSection.getAttribute('videoSrc').includes('start')){
var startTime = youtubeSection.getAttribute('videoSrc').split("start=");
var startTime = startTime[1].split('&',1);
var Start = startTime[0]
if (youtubeSection.getAttribute('videoSrc').includes('end')){
var endTime = youtubeSection.getAttribute('videoSrc').split("end=");
var End = endTime[1];
}
}
var player = {
"playerName": playerName,
"videoId": vidID,
"vidTitle": title,
"type": type,
"startSeconds": Start || null,
"endSeconds": End || null,
"started": 0
}
players.push(player)
})
var playedIds = [];
var endedIds = [];
if (players.length > 0) {
document.head.append(Object.assign(document.createElement('script'), {
src: 'https://www.youtube.com/iframe_api'
}))
window.onYouTubeIframeAPIReady = function() {
var hasVideos = document.getElementsByClassName('youtubeVid');
for(var i = 0; i < hasVideos.length;i++) {
var curplayer = createPlayer(players[i]);
}
};
function createPlayer(playerInfo) {
for(var i = 0; i < players.length ;i++) {
return new YT.Player(playerInfo.playerName, {
videoId: playerInfo.videoId,
playerVars: {rel: 0, showinfo: 0, ecver: 2},
startSeconds: playerInfo.startSeconds,
endSeconds: playerInfo.endSeconds,
events: {
'onReady': function (e) {
e.target.cueVideoById({
videoId: playerInfo.videoId,
startSeconds: playerInfo.startSeconds,
endSeconds: playerInfo.endSeconds,
});
console.log('video ready');
}
}
});
}
}
}
}
尝试在html上使用不同的ID
<div id="K1QICrgxTjA_1" data-step="1" class="youtubeVid" videosrc="https://www.youtube.com/watch?v=K1QICrgxTjA" videoid="K1QICrgxTjA"></div>