javascript - 根据结果​​在测验结束时按 ID 加载不同的 YouTube 视频

标签 javascript html css youtube switch-statement

我快完成了!

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

一切尽在掌握:https://jsfiddle.net/funkefiddle/tsnr8hra/

我有一个多问题测验。结果记录在一个对象中。在测验结束时,当“结果”div 显示 == 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() 函数相关的这个函数,这样视频就不会播放用户完成测验的整个时间。

请暂停。

编辑:我修改了代码以反射(reflect)以下两个建议。将 if 评估更改为不查看 div 显示是无还是 block 。还将链接的 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"
    }

最佳答案

试试这个 ;)

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

After return statement function control is transferred from where function invoked;

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

关于javascript - 根据结果​​在测验结束时按 ID 加载不同的 YouTube 视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490942/

相关文章:

html - 在没有 rtl 的表中将文本溢出到左侧

html - 将标题缩进绑定(bind)到段落

css - 创建表格更改列背景颜色

javascript - 我正在尝试使用 Javascript 来显示图像

javascript - 链接(或可链接的 DIV?)与背景图片 + 突出显示

javascript - 如何修改此 jQuery 插件 slider 的滚动和方向?

javascript - 必须使用 import 加载 ES Module .eslintrc.js

css - 在div中拉伸(stretch)文本

html - 为什么我无法在表单后的导航栏上保留任何内容?

javascript - 来自数据库的值没有出现在 php 中