首页 > 解决方案 > 很难解决的问题!:: TypeError: player.loadVideoById 不是函数

问题描述

$('#myModal').on('show.bs.modal'被调用。我明白了:

TypeError: player.loadVideoById 不是函数。(在 'player.loadVideoById(x)' 中,'player.loadVideoById' 未定义)

https://jsfiddle.net/rdbj3ty1/5/

在 JS Fiddle 中,代码可以工作,但是当我将它添加到我的代码库时,它会停止工作。我有很多它必须干扰的其他 js 代码和 CSS 代码。有没有办法防止干扰?也许用块包装我的 js 代码或添加更具体的引用?命名空间是问题吗?如果是这样,我该怎么做?

我真的不知道该尝试什么。我在这上面花了 2 天时间,却一无所获。

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

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'novideoid',
      events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
                           });
  }


  // 4. The API will call this function when the video player is ready.

  function onPlayerReady(event) {

    $('.open-popup').click(function() {
      event.target.playVideo();
    });

    $('.close-popup').click(function(e) {
      player.stopVideo();
    });

  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if(event.data === 0) {           
      $('.close.close-popup').click();
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
  
 $(function () { 
 onYouTubeIframeAPIReady();
   $('#myModal').on('show.bs.modal', function(e) {
     
       var videoId = $(e.relatedTarget).data('video-id');
       var x = new String(videoId);
       player.loadVideoById(x); 

  });

});

标签: javascriptjqueryjquery-eventsyoutube-iframe-api

解决方案


推荐阅读