嵌套函数不工作在JavaScript (YouTube API)



我需要显示一个视频时启动按钮被点击,当视频结束时,它应该重定向到一个网站。问题是,视频正在播放onLoad。我怎么能播放只有点击按钮。

下面是我的代码: HTML

<a onClick="myvideo()" class="waves-effect waves-light btn-large big"><i class="material-icons right">cloud</i>LAUNCH</a>
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>

JS

function mySite() {
    window.open('http://www.spark2k15.com','_self');
}

// create youtube player
var player;
function myvideo() {
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'xgRbxO94GRQ',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }
    // autoplay video
    function onPlayerReady(event) {
       event.target.playVideo();
    }
    // when video ends
    function onPlayerStateChange(event) {        
        if(event.data === 0) {          
            // alert('done');
            mySite();
        }
    }
}

从你的代码中,视频不应该被播放,因为onYouTubePlayerAPIReady似乎没有暴露给api调用。

你应该做的是:

  1. 移除myvideo功能块

  2. onYouTubePlayerAPIReady变为addEventListener变为<a>,并在处理程序中创建玩家

工作的jsfield .

HTML

解决

<a id="clickPlay" href="#" class="waves-effect waves-light btn-large big"><i class="material-icons right">cloud</i>LAUNCH</a>
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
// Shouldn't the api be this line? 
// Also, make sure that your function exposed for the api should be declared before api loaded.
<script src="https://www.youtube.com/iframe_api"></script> 

JS:

function mySite() {
    window.open('http://www.spark2k15.com','_self');
}
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
    var anchor = document.getElementById('clickPlay');
    // Only when the anchor is clicked, we create the video.
    anchor.addEventListener('click', function(e) {
        e.preventDefault();
            player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'xgRbxO94GRQ',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    });
}
// autoplay video
function onPlayerReady(event) {
    event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {        
    if(event.data === 0) {          
        // alert('done');
        mySite();
    }
}

相关内容

  • 没有找到相关文章

最新更新