如何在Javascript中触发某个事件

时间:2013-03-29 19:44:23

标签: javascript arrays random

首先对不起的问题感到抱歉,我不知道如何用一句话写好。

这是我的场景,我正在制作一个游戏,其中3张图片显示在屏幕上,并伴随着一个单词。这些图片和文字来自数据库。

数据输入到数据库中,因此对于每个单词时间输入一个单词,图片也会随之上传。

所有这些单词和图像集都从数据库中提取并放入JavaScript数组中。然后,我随机从一个数组中选择了3个图像并将它们放在另一个数组中,然后随机从第二个数组中选取一个单词。

我的问题是你如何将我选择的单词与正确的图像联系起来,然后当用户点击正确的图片时,屏幕上会出现“Well Done”的情况?

这是我的数组布局: -

   var items = [
          {name:'Coch',image:'upload/coch.png'},                                                                                   {name:'Glas',image:'upload/glas.png'},
     {name:'Melyn',image:'upload/melyn.png'},{name:'Ci',image:'upload/dog.jpg'},
      {name:'Cath',image:'upload/cath.jpg'},{name:'Gwyrdd',image:'upload/gwyrdd.png'},
     {name:'Un',image:'upload/un.jpg'},{name:'Dau',image:'upload/dau.jpg'},
     {name:'Tri',image:'upload/tri.jpg'},{name:'Bochdew',image:'upload/bochdew.jpg'},
     {name:'Piws',image:'upload/piws.png'}      ];

这是我的完整代码: -

       <!DOCTYPE html>

      <html lang="en">

             <div id="choosecat">
             <form method="get" action="playgame.php"       autocomplete="off">

                       <fieldset>
                          <legend>Choose Category</legend> 


                          <label>Category: <select name="topic">

                          <option value="%">All</option>
                           <option value="Animals">Animals</option>
                          <option value="Numbers">Numbers</option>
                          <option value="Colours">Colours</option>

                           </select></label>

                           <input type="submit" id="submitbutton" value="Go" />

                      </fieldset>


                        <br />




                  </form>


                  <?php 

                    $topic = $_GET['topic'];

                   $topic_choice = htmlspecialchars($topic,  ENT_QUOTES);



                   ?>


                        </div>

        <head>
              <title></title>



        <link rel="alternate stylesheet" type="text/css" title="red"
           href="gameplay.css">

        <link rel="stylesheet" type="text/css" title="blue"
       href="theme1.css">

      <link rel="alternate stylesheet" type="text/css" title="pink"
    href="theme2.css">

    <script src="js/stylesheets.js" type="text/javascript"></script>
        <script src="js/jquery.js" type="text/javascript"></script>
        <script src="js/javascript.js" type="text/javascript"></script>


      <script>

   var items = [
      <?php
       $con = mysql_connect("localhost","admin","password");
      if (!$con) {
        die('Could not connect: ' . mysql_error());
       }
      mysql_select_db("learning_game", $con);
      $result = mysql_query("SELECT * FROM data WHERE category LIKE '$topic_choice' ");
      $first = true;



      while ($row = mysql_fetch_array($result)) {
        if (!$first) {
          echo ",";
        }
        $first = false;
        echo "{name:'" . $row['word'] . "',image:'" . $row['image'] . "',video:'" .     $row['video'] . "',audio:'" . $row['audio'] . "'}";
    }
      mysql_close($con);
      ?>
     ];
    for (var i = 0; i < items.length; i += 1) {
        //document.getElementsByTagName('div')[0].innerHTML += items[i].name + " / " + items[i].image + "<br />\n";
        }  

           document.write("<br /> <br /> <br />");





    console.log(items);
    top.items = items;

        var images = new Array();
         var list = document.getElementsByTagName('div')[0];
         var names = new Array()
        var videos= new Array()
        var audios= new Array()

             for(i = 0; i < 3; i++) {

          // Choose a random item and removes it from the array
            var item = items.splice(Math.floor(Math.random() * items.length), 1)[0];

           // Create the image element and set its src attribute
           images[i] = document.createElement('img');
          images[i].src = item.image;

          videos[i] = document.createElement('video');
          videos[i].src = item.video;
             //video.controls = true;


              audios[i] = document.createElement('audio');
             audios[i].src = item.audio;
             //audio.controls = true;

             // var audio = new Audio(video);



             // Add it to your container element

           images.src = item.image;
            videos.src = item.video;
        audios.src = item.audio;
        names[i] = item.name;




          }
         var randomIndex = Math.floor(Math.random() * 3);
          var name_to_display = names[randomIndex];
         var image_to_display = images[randomIndex];
        var video_to_display = videos[randomIndex];
        var audio_to_display = audios[randomIndex];


      var data = new Array();


   document.getElementById("one").appendChild(images[0]);
   document.getElementById("two").appendChild(images[1]);
   document.getElementById("three").appendChild(images[2]);


       document.body.appendChild(audio[0]);
  document.getElementById("whitebox").appendChild(video[1]);
   document.getElementById("whitebox").appendChild(video[2]);


    /*document.getElementById("one").appendChild(data.image[0]);
    document.getElementById("two").appendChild(data.image[1]);
     document.getElementById("three").appendChild(data.image[2]);
   */



          </script>

       </head>

       <body onload="set_style_from_cookie()">
        <div id="container">




            <div id="header">
                <br />
                <img id="mabon" src="mabon.png"/>

            </div>

                       <div id="radio">
                          <input class="centerradio" type="checkbox"  name="theme" onclick="switch_style('red');return false;" value="Main">Mabon A Mabli
                            <input id="top_radio_button" class="centerradio" type="checkbox" name="theme" onclick="switch_style('blue');return false;" value="Blue Theme">Pastel <br>
                          <input class="centerradio" type="checkbox" name="theme" onclick="switch_style('pink');return false;" value="Pink Theme">Plain<br />
                       </div>

                     <div id="change_cat">




           <div id="random">


           <div class="wrapper">
               <div id="one" class="item"></div>

             <div id="two" class="item"></div>

               <div id="three" class="item"></div>

          </div>


          <div id="wordwrapper">

              <div id="worddiv">

                  <p id="wordtext"><script>document.write('-- '+name_to_display+' --');</script></p>

             </div>



          </div>


       <div id="videocorner">
        Video Corner
       </div>   

       <div id="videodiv">
          <video width="300" height="230" controls>
               <source src="bbc_three.mp4" type="video/mp4">
               <source src="movie.ogg" type="video/ogg">
               Your browser does not support the video tag.
          </video>
      </div>




      <div id="linkdiv">
               <a href="#" id="link" class="myButton">Makaton</a>
          </div>




              <div id="sounddiv">
      <!--
    <audio autoplay="3" controls>
      <source src="hover.wav" type="audio/wav">
     <source src="hover.mp3" type="audio/mpeg">
      Your browser does not support the audio element.
      </audio>
        -->




     </div> 
       <img src="cartoon.png" id="help" height="200px">
     </div>     











      <div id="whitebox">
        <script>

            </script>
      </div>


          <div id="disp">

       <script>
         var audio = document.createElement('audio');
               audio.src = audio_to_display.src;
         //audio.src = item.audio;
         audio.controls = true;
         document.getElementById("disp").appendChild(audio);
     </script>



      <script>
                document.getElementById("one").appendChild(images[0]);
          document.getElementById("two").appendChild(images[1]);
         document.getElementById("three").appendChild(images[2]);


         var video = document.createElement('video');
         video.src = video_to_display.src;
         //video.src = item.video;
         video.controls = true;
         document.getElementById("disp").appendChild(video);
        </script>

          </div>

        </body>
     </html>

对于代码的质量感到抱歉,我是Javascript和Web开发的新手。

提前感谢您的回复。

1 个答案:

答案 0 :(得分:0)

基本上,你需要3件事:

  1. 每个图像上的alt标记,用于标识它是什么
  2. 正确答案的ID,对应于其中一张图片的alt标签
  3. 每张图片上的点击功能,用于将图片的ID与正确答案进行比较,如果正确,则会显示警告。
  4. 这样的事情:

    // Create the image element and set its src attribute
    images[i] = document.createElement('img');
    images[i].src = item.image;
    images[i].alt = item.name;
    images[i].onclick = function(e) {
        if (e.target.alt == name_to_display)
        {
            alert('good job!');
        }
    };
    

    应创建一个如下所示的图像标记:

    <img alt="Brown Dog" src="/images/browndog.jpg" />
    

    单击时,将其alt标记的值与保存的name_to_display(我假设您要保留正确答案的值)进行比较,如果相同,则显示警报。如果name_to_display在正确的范围内,这应该有效。