2011-11-18 22 views
0

但是,我已經設置了一些測試代碼,用於在YouTube視頻中加載一個測試代碼,然後在計劃停止視頻的鏈接上添加一個jQuery點擊事件當我點擊鏈接時,我得到的錯誤:未捕獲TypeError:對象[對象對象]沒有方法'stopVideo'當點擊事件被觸發時,關於製作YouTube視頻的建議

任何人都可以提出我可能會出錯哪裏呢?

<div id="container"> 
    <a href="#">This is the link</a> 

    <br /><br /> 
    <br /><br /> 

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


<script> 
     var tag = document.createElement('script'); 
     tag.src = "http://www.youtube.com/player_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 onYouTubePlayerAPIReady() { 
      player = new YT.Player('player', { 
      height: '390', 
      width: '640', 
      videoId: 'u1zgFlCw8Aw' 
      }); 
     } 

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

     $(document).ready(function() { 
      $('a').click(function(e) { 
       player.stopVideo(); 
       e.preventDefault(); 
      }); 
     }); 
</script> 

回答

3

您的代碼片段按照預期在fiddle中工作。此外,由於postMessage實施方面的限制,YouTube Frame API不會在file:///協議中運行。

我之前創建了一個YouTube API的自定義實現,可在YouTube iframe API: how do I control a iframe player that's already in the HTML?處獲得。我通過file:///協議成功執行stopVideo方法。

如果你在網上運行你的代碼,我只能想到一個其他的原因:您正在嘗試在鏈接點擊之前播放器準備就緒。爲了解決這個問題,你的合併功能:

function onPlayerReady(event) { 
     event.target.playVideo(); 
     $('a').click(function(e) { //<--- Binds event to ALL anchors! Are you sure? 
      player.stopVideo(); 
      e.preventDefault(); 
     }); 
    });