2015-04-17 171 views
0

我試圖用Youtube播放器API來切換視頻,當我關閉一個模式框。使用Youtube Iframe API

這裏是我的代碼,它創建了iframe,但是按鈕沒有對上述iframe進行API控制。

<div id="player"></div>  

<script type="text/javascript"> 
var tag = document.createElement('script'); 
tag.src = "http://www.youtube.com/player_api"; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

var player; 
function onYouTubePlayerAPIReady() { 
    player = new YT.Player('player', { 
     height: '500', 
     width: '800', 
     videoId: 'f37MOGHMrlI' 
     }); 
} 

$(".toggle1").click(function(){ 
    alert("Pausing " + player);//is undefined :(
    player.pauseVideo(); 
}); 

</script> 

任何人都知道缺失的是什麼?

回答

0

雖然有必要明確地看到整個頁面結構,因爲您的腳本位於body,我的猜測是,類toggle1的按鈕尚未添加到DOM您的click處理程序已分配。或者將處理器分配包裝在$(document).ready

function onYouTubePlayerAPIReady() { 
    player = new YT.Player('player', { 
     height: '500', 
     width: '800', 
     videoId: 'f37MOGHMrlI' 
     events: { 
      onReady: configureButton 
     } 
     }); 
} 

function configureButton() { 
    $(".toggle1").click(function(){ 
    player.pauseVideo(); 
    }); 
}