javascript - Youtube API 不适用于动态生成的对象数组

标签 javascript arrays object youtube-api

我在使用 Youtube API 时遇到了这个看似奇怪的问题... 我正在编写一个脚本,该脚本将检测页面上的所有 YouTube 视频,然后使用 Youtube API 替换它们。这样我就能够检测 API 事件,例如视频结束时、显示消息。我正在为页面上的每个视频创建一个 YouTube 播放器对象的新实例。到目前为止一切都很好。

我动态生成视频容器,并将视频容器 ID 和视频 ID 保存到对象数组中(下面是我当前的代码)。

奇怪的是,当我动态生成这个对象数组时(使用 array.push() ),Youtube API 不起作用。 如果我显式声明这个对象数组,Youtube API 就可以正常工作。

<小时/>

更清楚地说,这不适用于 Youtube API(插图示例):

var playerInfoList = [];
foreach loop{
   playerInfoList.push( object );
}

截图:http://i.gyazo.com/a0f21db4fb60e921be5cc1d1d52f948f.png

<小时/>

这有效:

var playerInfoList = [
    {containerID:'social_share_custom_0', videoID:'KSyHWMdH9gk'},
    {containerID:'social_share_custom_1', videoID:'b-u5LE6X6ME'}
];

截图:http://i.gyazo.com/39bce30e4ebfb21119d48bbaf818d491.png

<小时/>

我制作了一个示例页面来演示这一点,如下:

<html>
<head>

</head>
<body>

<?php
    $content = '
    <h3>This is a sample page to demonstrate the issue...</h3>
    Text before <br /><br />
    <iframe width="560" height="315" src="//www.youtube.com/embed/KSyHWMdH9gk?rel=0" frameborder="0" allowfullscreen></iframe>
    Text in between.
    <iframe width="560" height="315" src="//www.youtube.com/embed/b-u5LE6X6ME?rel=0" frameborder="0" allowfullscreen></iframe>
    <br /><br />Text after.';

    $return_HTML  = '';

    // match any iframes
    $pattern = '~<iframe.*</iframe>|<embed.*</embed>~';
    preg_match_all($pattern, $content, $matches);


    // START Youtube Script
    $YT_scripts = '
            <script>
                /*
                ** Array of objects
                ** params containerID, videoID
                */
                var playerInfoList = []; ';

    $index = 0;
    foreach ($matches[0] as $match) {

        $embedPattern = '%(?:https?://)?(?:www\.)?(?:youtu\.be/| youtube\.com(?:/embed/|/v/|/watch\?v=))([\w-]{10,12})[a-zA-Z0-9\< \>\"]%x';

        $res=false;
        $res = preg_match($embedPattern, $match, $embedOutput); 

        if( $res ){
            $YT_scripts .= '
            //new object
            var newItem = {containerID:"social_share_custom_'.$index.'", videoID:"'.$embedOutput[1].'"};

            //put it into array
            playerInfoList.push(newItem);';             

            $wrappedframe = '<div class="social_share_custom_video_container" id="social_share_custom_'.$index.'"></div>';
            $content = str_replace($match, $wrappedframe, $content);
        }
    $index++;
    }

    $content .= $YT_scripts.'</script>';    
    $return_HTML .= $content;   

    echo $return_HTML;
?>

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

/*
// if we declare this explicitly, Youtube API works.
// if this array if generated DYNAMICALLY (if we comment this out), Youtube API does not work.
var playerInfoList = [
    {containerID:'social_share_custom_0', videoID:'KSyHWMdH9gk'},
    {containerID:'social_share_custom_1', videoID:'b-u5LE6X6ME'}
];
*/

console.log( 'Object array length: ' + playerInfoList.length );

    function onYouTubeIframeAPIReady() {
        if(typeof playerInfoList === 'undefined')
            return; 

        for(var i = 0; i < playerInfoList.length;i++) {
            var player = createPlayer(playerInfoList[i]);
        }
    }

    function createPlayer(listItem){
        console.log( listItem.containerID + ' - ' + listItem.videoID );

        return new YT.Player(listItem.containerID, {
            height: '350',
            width: '480',
            videoId: listItem.videoID,
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange,
                'onError' : onPlayerError
            }
        });
    }

    // autoplay video
    function onPlayerReady(event){
        // video is Ready
    }

    // when video ends
    function onPlayerStateChange(event) {        
        console.log(event);

        if(event.data == 0) {
            // video Ended
            // showEndVideoPrompt();
            console.log('Video Ended.');
        }
        else if (event.data === 1) {
            //video Started
        }
        else if (event.data === 2) {
            //video Stopped
        }           
    }

    function onPlayerError(event) {
        // video Error
    }
</script>

</body>
</html>

我花了将近两天的时间尝试不同的事情,但仍然不知道为什么会发生这种情况。我在这里搜索了类似的问题,但没有找到任何其他与动态生成的对象数组和 Youtube API 相关的特定问题。

任何解决此问题的帮助将不胜感激。如果您需要更多信息,请告诉我。 感谢所有伸出援助之手的人:)

最佳答案

问题是由于您用于提取视频 ID 的正则表达式造成的。最后一点[a-zA-Z0-9\< \>\"]正在破坏videoID通过消耗 ID 的最后一个字符,而不是与其余字符一起捕获。删除它应该可以解决问题。

关于javascript - Youtube API 不适用于动态生成的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236015/

相关文章:

javascript - Logo 应仅在滚动条上可见

javascript - if 语句中的 in do 或 意味着什么?

c - 排序 2 个大数组

arrays - 我们可以使用二分搜索来查找排序数组中最常出现的整数吗?

javascript - 无法单击 Flash 对象

javascript - 同步 XHR 弃用

javascript - 如何比较 Javascript 中的数组和对象?

c# - 你如何处理对象类型切换?

python - 我想在 python 中创建一个模拟对象

php - 将 JSON 字符串解析为数组,而不是对象