2016-12-12 63 views
0

我正在使用YouTube Iframe,如下所示。我希望在API加載後立即讓我的玩家加載點擊按鈕。如何獲取YouTube API以加載onclick?

我創建了一個系統,我的網站用戶可以選擇將哪些視頻加載到播放列表中,因此我無法對YouTube視頻ID進行硬編碼。是否可以創建一個onclick函數來觸發加載播放器的事件?如果是這樣,怎麼樣?

非常感謝!

<script> 
    // 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: 'M7lc1UVf-VE', 
     events: { //CAN I REPLACE THE ONREADY EVENT WITH ONE 
     'onReady': onPlayerReady, //THAT FIRES ONCLICK? 
     'onStateChange': onPlayerStateChange 
     } 
    }); 
    } 

    // 4. The API will call this function when the video player is ready. 
    function onPlayerReady(event) { 
    event.target.playVideo(); 
    } 

回答

1

你可以做以下類似代碼

var tag = document.createElement('script'); 
tag.src = "https://www.youtube.com/iframe_api"; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

var video_id = '' //Desired video ID 
var player; 
$('LOAD_BUTTON').on('click', function() { 
    // Load player when LOAD_BUTTON is clicked 
    player = new YT.Player('player', { 
    height: '390', 
    width: '640', 
    videoId: video_id, 
    events: { 
     'onReady': onPlayerReady, 
     'onStateChange': onPlayerStateChange 
    } 
    }); 
}); 

function onPlayerReady(event) { 
    $('PLAY_BUTTON').on('click', function() { 
    // Play video when PLAY_BUTTON is clicked 
    event.target.playVideo(); 
    }); 
} 
+0

太謝謝你了。這工作完美。我停止播放按鈕,並將其全部裝入加載按鈕中。你不知道我需要多少這個解決方案,多虧了一百萬。 –

+0

很高興幫助,標記我接受的答案也將幫助我很多:) – osk2