动态创建的iFrame上的YouTube iFrame API [英] YouTube iFrame API on dynamically created iFrame

查看:107
本文介绍了动态创建的iFrame上的YouTube iFrame API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用YouTube iFrame API,因为我需要能够暂停使用jQuery动态创建的视频。我有以下代码:

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();
    
  });
}

然而,我得到这个呃ror:
Uncaught TypeError:无法读取属性'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.

推荐答案

您通过使用关键字将player重新定义为第一次点击回调的本地变量var了。摆脱第二个var

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');

  })

这篇关于动态创建的iFrame上的YouTube iFrame API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆