YouTube iFrame API on dynamically created iFrame

2019-07-04 21:27发布

I'm using the YouTube iFrame API because I need to be able to pause a video dynamically created with jQuery. I have the following code:

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

$(function() {

  var player;
  
  $(document).on('click', 'button', function(){
    
    media = $(this).data('media');
    
    $('#player').append('<div id="media"><iframe width="200" height="200" src="http://www.youtube.com/embed/' + media + '?autoplay=1" frameborder="0" allowfullscreen id="media-player"></iframe>');
    
    var player = new YT.Player('media-player');
    
  })
  
  
  $('#pause').click(function(){
    
    player.pauseVideo();
    
  });
}

However, I'm getting this error: Uncaught TypeError: Cannot read property 'pauseVideo' of undefined

Can anyone point me in the right direction. Any help is appreciated.

1条回答
地球回转人心会变
2楼-- · 2019-07-04 22:00

You re-defined "player" as a local variable to the first click callback by using the keyword "var" again. Get rid of the second "var"

(function() {

  var player;

  $(document).on('click', 'button', function(){

    media = $(this).data('media');

    $('#player').append('<div id="media"><iframe width="200" height="200" src="http://www.youtube.com/embed/' + media + '?autoplay=1" frameborder="0" allowfullscreen id="media-player"></iframe>');

    player = new YT.Player('media-player');

  })
查看更多
登录 后发表回答