2014-09-21 67 views
0

我試圖跟蹤我網站上的任何事件YouTube視頻。 爲什麼這不起作用? HTML:YouTube API - addEventListener不工作

<div> 
    <iframe id="video-block" width="560" height="315" src="//www.youtube.com/embed/123456?enablejsapi=1 " frameborder="0" allowfullscreen ></iframe> 
</div> 

JS:

var tag = document.createElement('script'); 

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

    function onYouTubeIframeAPIReady() { 
     alert("1"); 
     ytplayer = new YT.Player('video-chia'); 
     ytplayer.addEventListener('onStateChange', function(e) { 
      alert('State change'); 
     }); 

    } 

回答

-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 player; 
    function onYouTubeIframeAPIReady() { 
    player = new YT.Player('player', { 

     videoId: 'M7lc1UVf-VE', 
     events: { 
     'onReady': onPlayerReady, 
     'onStateChange': onPlayerStateChange 
     } 
    }); 

    } 

    function onPlayerReady(event) { 
    event.target.playVideo(); 
    } 

    var done = false; 
    function onPlayerStateChange(event) { 
    if (event.data == YT.PlayerState.PLAYING && !done) { 
     setTimeout(stopVideo, 6000); 
     done = true; 
    } 
    } 
    function stopVideo() { 
    player.stopVideo(); 
    } 
+0

我很好奇。什麼狀態的變化可以捕捉到這一點? Regards – loveNoHate 2014-09-21 08:49:13

+1

哈哈,這段代碼來自YouTube API的文檔。您至少可以發佈代碼的來源... @DOCASAREL請參閱https://developers.google.com/youtube/iframe_api_reference?hl=fr部分:**入門** – mpgn 2014-09-21 10:36:59

相關問題