【问题标题】:Load different youtube videos by ID at the end of a quiz depending on the outcome根据结果​​在测验结束时按 ID 加载不同的 youtube 视频
【发布时间】:2016-04-08 03:21:57
【问题描述】:

我快完成了!

对于那些在家玩的人,我一直在尝试为一个 uni 项目构建一个香草 JavaScript 测验。我从 stackoverflow 的优秀人员那里得到了很多帮助。希望这是最后一个问题:)

万事大吉:https://jsfiddle.net/funkefiddle/tsnr8hra/

我有一个多问题测验。结果记录在一个对象中。在测验结束时,当“结果”div 为 display == block 时,一个函数将计算出最终答案并编辑 innerHTML。

我想根据最终答案结果播放四个不同的 Youtube 视频之一。

我的 JS:

        if (document.getElementById("results").style.display == "block") { // Check that we are on the 'results' stage of the quiz, ie the final page. 
            return loadYTPlayer();  

             if (finalResults == "Ninja") {
             player.loadVideoById(d2iD_j1MrJc); 
             console.log('Ninja: d2iD_j1MrJc')
             }
             else if (finalResults == "Robot") {
             player.loadVideoById(B1BdQcJ2ZYY);
             console.log('Robot: B1BdQcJ2ZYY')
             }
             else if (finalResults == "Pirate") {
             player.loadVideoById(TzMbGPa-Vus);
             console.log('Pirate: TzMbGPa-Vus')
             }
             else if (finalResults == "Zombies") {
             player.loadVideoById(TzMbGPa-Vus);
             console.log('ZombiePirates? TzMbGPa-Vus') // Zombies are lame. Moar pirates pls!
             }
          }
        }

function finalResults() {   // Get the values of the answerData object to work out which result is the highest. We need to compare the results somehow.

    var theAnswer = Object.keys(answerData).reduce(function(a, b){ return answerData[a].score > answerData[b].score ? a : b });
    return theAnswer;
}

// Now for a prize for all those loyal quiz participants.
function loadYTPlayer() {

      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: '100%',
          width: '100%',
          videoId: '',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

     function onPlayerReady(event) {
       event.target.playVideo();
    }

      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {

          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }

我知道我没有正确调用函数 loadYTPlayer(),但是如果我没有将它放入函数中,视频会在页面加载后立即开始播放(尽管 div 被隐藏)。

我知道我可以使用 player.loadVideoById(vidID) 开始播放自定义视频的视频我只是不确定何时调用与 loadYTPlayer() 函数相关的此函数,以便视频不播放用户完成测验的整个时间。

请停下来。

编辑:我修改了代码以反映以下两个建议。将 if 评估更改为不查看 div 显示是无还是块。还将链接的 IF 更改为开关。 我没有收到控制台错误“Uncaught TypeError: Cannot read property 'loadVideoById' of undefined”

if (nextQuestion == "results") { // If the nextQuestion is equal to results (the ID of the final div) we are at the end of the quiz and need to do a bunch of stuff
        document.getElementById("results").style.display = "block";

        document.getElementById("finalResulthere").innerHTML = "<p>You are a " + finalResults() + ", congratulations!</p><p>Now kick back and enjoy your prize.</p>"; // Modify the innerHTML to display the output of the finalResults function. This should display a paragraph telling us what our personality is.

        loadYTPlayer(); // We have to load the YouTube iFrame API


        var videoId = '';
        switch (finalResults) { // Find the correct video file to load by comparing the finalResults output to the available names in this switch statement. If one of them matches, assign the correct videoId to the variable of the same name. 
        case "Ninja":
            videoId = "d2iD_j1MrJc";
            console.log('Ninja: d2iD_j1MrJc');
            break;

        case "Robot":
            videoId = "4YJ3BTKMILw";
            console.log('Robot: 4YJ3BTKMILw');
            break;

        case "Pirate":
            videoId = "TzMbGPa-Vus";
            console.log('Pirate: TzMbGPa-Vus');
            break;

        case "Zombies":
            videoId = "TzMbGPa-Vus";
            console.log('ZombiePirates? TzMbGPa-Vus'); /* Zombies are lame. Moar pirates pls! */
            break;
        }

        player.loadVideoById(videoId); // Start playing the video that matches the final personality type. 

    } else { // If the nextQuestion is not 'results' just display the next question in sequence. 

        document.getElementById(nextQuestion).style.display = "block"
    }

【问题讨论】:

  • 根据元素的可见性来跟踪状态根本不好......您应该改用变量。
  • 我不知道。但我可以想象。好的,所以我添加了一个 var 来跟踪当前的问题 div id。然后修改 IF 以检查 currnetQuestion var 是否为 'results' var currentQuestion = this.parentElement.id; // 获取当前 div 的 ID 以跟踪我们在哪里 console.log("当前元素 ID 是:" + currentQuestion); if (currentQuestion == "results")

标签: javascript html css youtube switch-statement


【解决方案1】:

试试这个;)

 // Check that we are on the 'results' stage of the quiz, ie the final page. 
 if (document.getElementById("results").style.display == "block") {
   /* removed return from here as we want to execute code after this statement also. */
   loadYTPlayer();  

   var videoId = '';
   switch (finalResults) {
     case "Ninja":
       videoId = "d2iD_j1MrJc"; 
       console.log('Ninja: d2iD_j1MrJc')
       break;
     case "Robot":
       videoId = "B1BdQcJ2ZYY";
       console.log('Robot: B1BdQcJ2ZYY');
       break;  

     case "Pirate":
       videoId = "TzMbGPa-Vus";
       console.log('Pirate: TzMbGPa-Vus');
       break;

     case "Zombies":
       videoId = "TzMbGPa-Vus";
       console.log('ZombiePirates? TzMbGPa-Vus'); /* Zombies are lame. Moar pirates pls! */
       break;
   }
   player.loadVideoById(videoId);
 }
 }

return 语句后函数控制从函数调用处转移;

将非数值用双引号括起来"non numeric value here";

【讨论】:

  • 出于某种原因,我决定使用 if 语句来加载整个最后一个 div 是个好主意。并从 style.display 中删除 IF。现在视频根本没有加载......再次。更新了 jsfiddle jsfiddle.net/funkefiddle/tsnr8hra/2
  • 为此,您需要在使用之前加载 youtube api,因为加载和初始化 api 需要时间;所以你可以在页面加载时加载它;
  • 如果我将 onYouTubeIframeAPIReady() 函数更改为包含 videoId,它将在第一次按下“开始测验”按钮后开始在后台播放视频 - 然后当它到达最后一页时停止播放并重新加载没有 videoId 的 iframe。
  • 从当前代码看来onYouTubeIframeAPIReady()里面的代码在api加载后没有被触发;你可以确认这是在 api 加载后执行的吗?
  • 是的,视频 iframe 本身正在加载,但显示“发生错误。请稍后再试”。我目前的假设是我们在 switch 中分配的 videoId 没有达到 onYouTubeIframeAPIReady() 。控制台显示 Uncaught TypeError: Cannot read property 'loadVideoById' of undefined 而且我刚刚注意到 switch 中的 console.log 没有将任何内容记录到控制台。
【解决方案2】:

尝试传递一个字符串:

player.loadVideoById("d2iD_j1MrJc");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 2012-05-14
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2022-12-02
    • 2012-06-02
    相关资源
    最近更新 更多