2016-10-17 3 views
1

Мне нужен свежий набор глаз. Я просмотрел stackoverflow для типичного «Can not read property» innerHTML «null» и, похоже, обычно вызван тем, что элемент DOM не загружается до вызова сценария для внесения изменений. Однако моя ошибка создается после нажатия на элемент, поэтому я считаю, что он уже существует.Невозможно прочитать свойство «innerHTML» null - Не кажется ли DOM

Номер строки ошибки - это оператор if: if(document.getElementById('tile').innerHTML=="" && memory_values.length < 2), содержащийся в функции memoryFlipTile.

Я считаю, что ошибка, вызванная функцией newBoard():

function newBoard() 
      { 

       // TODO reset variable for tiles flipped to equal 0 
       var reset = 0; 

       // TODO create a variable for output set equal to an empty string 
       var output = ""; 

       // TODO call anonymous function Array 
       Array.prototype.memory_tile_shuffle.call; 


       // TODO perform a for loop from index 0 to the length of memory_array 
       for(var i = 0; i < memory_array.length; i++) 
       { 


        // TODO concatenate variable "output" to equal 
        //  '<div id="tile_' 
        output+='<div id = "tile_'; 
        output+=i; 
        output+='" onClick="memoryFlipTile(this,\''; 
        output+=memory_array[i]; 
        output+='\')"></div>'; 


       // TODO update the document object, element id called 'memory_board', innerHTML 
       //  so it is equal to the output variable 
       document.getElementById("memory_board").innerHTML=output; 
       } 
      } 

В частности, я считаю, что я сделал ошибку в для цикла, но я не совсем уверен, что. Моя догадка заключается в том, что элементы, использующие функцию onClick, не имеют значений.

Вот полный код:

<!DOCTYPE html> 
<html> 
    <head> 
     <style> 
      div#memory_board 
      { 
       background:#CCC; 
       border:#999 1px solid; 
       width:800px; 
       height:540px; 
       padding:24px; 
       margin:0px auto; 
      } 
      div#memory_board > div 
      { 
       background: pink; 
       border:#000 1px solid; 
       width:71px; 
       height:71px; 
       float:left; 
       margin:10px; 
       padding:20px; 
       font-size:64px; 
       cursor:pointer; 
       text-align:center; 
      } 
     </style> 

    </head> 
    <body> 
     <!-- create a div with id attribute equal to "memory_board" --> 
     <div id = "memory_board" > 

     </div> 

    </body> 
</html> 

      <!-- in the script tag --> 
      <script> 

      // global variable declaration 

      // TODO declare array "memory_array" that contains 24 items, 12 pairs (e.g. A, A, B, B, etc...) 
      var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J','K','K','L','L']; 

      // TODO declare array "memory_values" with no data 
      var memory_values = []; 

      // TODO declare array "memory_tile_ids" with no data 
      var memory_tile_ids = []; 

      // TODO declare a variable for keeping tracking of how many tiles are flipped 
      var tiles_flipped; 



      // TODO add an anonymous function to the Array object called memory_tile_shuffle 
      Array.prototype.memory_tile_shuffle = function() 
      { 
       // TODO declare variable "length" set equal to the length of the array 
       var length = memory_tile_shuffle.length; 

       // TODO declare variable "rand" 
       var rand; 

       // TODO declare variable "temp" 
       var temp; 

       // TODO loop while the value of --length (using predecrement) is greater than 0 
       while(--length > 0) 
       { 
        //TODO set variable rand equal to Math.floor(Math.random() * (length + 1)) 
        var rand = Math.floor(Math.random() * (length + 1)) 

        // TODO set variable temp equal to this array at index rand 
        var temp = memory_tile_shuffle[rand]; 

        // TODO set this array index rand equal to this array index length 
        rand = memory_tile_shuffle.length; 

        // TODO set this array index length equal to temp 
        length = temp; 

       } 
      } 

      // TODO write function newBoard, no parameters, to reset data for the game 
      function newBoard() 
      { 

       // TODO reset variable for tiles flipped to equal 0 
       var reset = 0; 

       // TODO create a variable for output set equal to an empty string 
       var output = ""; 

       // TODO call anonymous function Array 
       Array.prototype.memory_tile_shuffle.call; 


       // TODO perform a for loop from index 0 to the length of memory_array 
       for(var i = 0; i < memory_array.length; i++) 
       { 


        // TODO concatenate variable "output" to equal 
        //  '<div id="tile_' 
        output+='<div id = "tile_'; 
        output+=i; 
        output+='" onClick="memoryFlipTile(this,\''; 
        output+=memory_array[i]; 
        output+='\')"></div>'; 


       // TODO update the document object, element id called 'memory_board', innerHTML 
       //  so it is equal to the output variable 
       document.getElementById("memory_board").innerHTML=output; 
       } 
      } 

      // TODO write function Tile with parameters tile and val 
      function memoryFlipTile(tile, val) 
      { 
       // TODO check if the innerHTML of object tile is equal to "" and 
       //  the length of array memory_values is less than 2 
       if(document.getElementById('tile').innerHTML=="" && memory_values.length < 2) 
       { 
        // style settings for the background of the tile object 
        tile.style.background = '#FFF'; 

        // TODO set object tile innerHTML equal to the val parameter 
        document.getElementById("tile").innerHTML= val; 

        // TODO check if the length of array memory_values equals 0 
        if(memory_values.length == 0) 
        { 
         // TODO call function push on array memory_values passing 
         //  val as an argument 
         memory_values.push(val); 

         // TODO call function push on array memory_tile_ids passing 
         //  tile.id as an argument 
         memory_tile_ids.push(tile.id); 

        } 
        // TODO check if the length of array memory_values equals 1 
        else if(memory_values.length == 1) 
        { 
         // TODO call function push on array memory_values passing 
         //  val as an argument 
         memory_values(val); 


         // TODO call function push on array memory_tile_ids passing 
         //  tile.id as an argument 
         memory_tile_ids(tile.id); 

         // TODO check if memory_values index 0 equals memory_values index 1 
         if(memory_values[0] == memory_values[1]) 
         { 
          // TODO update the value of variable tiles_flipped to be increased by 2 
          tiles_flipped += 2; 

          // TODO clear array memory_values 
          memory_values = []; 

          // TODO clear array memory_tile_ids 
          memory_tile_ids = []; 

          // TODO check to see if the whole board is cleared by 
          //  comparing the number of tiles_flipped being equal to 
          //  the length of array memory_array 
          if(tiles_flipped == memory_array.length++) 
          { 
           alert("The board has been cleared and a new board is being generate"); 
           // TODO using an alert dialog box inform the user that 
           //  the board has been cleared and a new board is 
           //  being generated 

           // TODO update object document, id 'memory_board', innerHTML 
           //  to be equal to "" 
           document.getElementById("memory_board").innerHTML= ""; 

           // TODO call function newBoard 
           newBoard(); 

          } 
         } 
         // otherwise 
         else 
         { 
          // TODO write function flip2Back so it flips the turned over tiles to 
          //  no longer be visible 
          function flip2Back() 
          { 
           // Flip the 2 tiles back over 
           // TODO declare variable tile_1 set equal to object document, 
           //  element id memory_tile_ids, index 0 
           var tile_1 = document.getElementById("memory_tile_ids[0]"); 

           // TODO declare variable tile_1 set equal to object document, 
           //  element id memory_tile_ids, index 1 

           // style settings for tile_1 
           tile_1.style.background = 'pink'; 
           tile_1.innerHTML = ""; 

           // style settings for tile_2 
           tile_2.style.background = 'pink'; 
           tile_2.innerHTML = ""; 

           // TODO clear array memory_values 
           memory_values = []; 

           // TODO clear array memory_tile_ids 
           memory_tile_ids = []; 
          } 

          // TODO call function setTimeout passing arguments function flip2Back 
          //  and the value 700 
          setTimeout(flip2Back(),700); 

         } 
        } 
       } 
      } 
     newBoard(); 
     </script> 
+0

Не видите где-нибудь, где вы создаете элемент с идентификатором «плитка». – Phil

ответ

0

Похоже, вы создаете несколько фрагментов с идентификаторами, как tile_1, tile_2 и т.д., но потом пытается найти что-то с идентификатором только tile. Ничто не имеет идентификатора только tile, поэтому поиск не работает. Вам нужно getElementById tile_x, где x - номер плитки, которую вы ищете.

В вашем йот, вы передаете в объекте, как this:

output+='" onClick="memoryFlipTile(this,\''; 

но в функции memoryFlipTile, вы используете строку "tile" вместо параметра tile, который передается в In. места, мы в настоящее время вы глядя на строку «плитки», вместо этого вы хотите посмотреть на переменной tile.id, как:

document.getElementById(tile.id) 

Вот минимальное воспроизводство: https://jsfiddle.net/orz89xwr/

0
your element is generated as id="tile_1" , "tile_2" etc.... 

and in javascript you are using following code<br> 
document.getElementById('tile').innerHTML<br> 
there is no any element of "tile" id. 


<br><br> 

<!DOCTYPE html> 
<html> 
    <head> 
     <style> 
      div#memory_board 
      { 
       background:#CCC; 
       border:#999 1px solid; 
       width:800px; 
       height:540px; 
       padding:24px; 
       margin:0px auto; 
      } 
      div#memory_board > div 
      { 
       background: pink; 
       border:#000 1px solid; 
       width:71px; 
       height:71px; 
       float:left; 
       margin:10px; 
       padding:20px; 
       font-size:64px; 
       cursor:pointer; 
       text-align:center; 
      } 
     </style> 

    </head> 
    <body> 
     <!-- create a div with id attribute equal to "memory_board" --> 
     <div id = "memory_board" > 

     </div> 

    </body> 
</html> 

      <!-- in the script tag --> 
      <script> 

      // global variable declaration 

      // TODO declare array "memory_array" that contains 24 items, 12 pairs (e.g. A, A, B, B, etc...) 
      var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J','K','K','L','L']; 

      // TODO declare array "memory_values" with no data 
      var memory_values = []; 

      // TODO declare array "memory_tile_ids" with no data 
      var memory_tile_ids = []; 

      // TODO declare a variable for keeping tracking of how many tiles are flipped 
      var tiles_flipped; 



      // TODO add an anonymous function to the Array object called memory_tile_shuffle 
      Array.prototype.memory_tile_shuffle = function() 
      { 
       // TODO declare variable "length" set equal to the length of the array 
       var length = memory_tile_shuffle.length; 

       // TODO declare variable "rand" 
       var rand; 

       // TODO declare variable "temp" 
       var temp; 

       // TODO loop while the value of --length (using predecrement) is greater than 0 
       while(--length > 0) 
       { 
        //TODO set variable rand equal to Math.floor(Math.random() * (length + 1)) 
        var rand = Math.floor(Math.random() * (length + 1)) 

        // TODO set variable temp equal to this array at index rand 
        var temp = memory_tile_shuffle[rand]; 

        // TODO set this array index rand equal to this array index length 
        rand = memory_tile_shuffle.length; 

        // TODO set this array index length equal to temp 
        length = temp; 

       } 
      } 

      // TODO write function newBoard, no parameters, to reset data for the game 
      function newBoard() 
      { 

       // TODO reset variable for tiles flipped to equal 0 
       var reset = 0; 

       // TODO create a variable for output set equal to an empty string 
       var output = ""; 

       // TODO call anonymous function Array 
       Array.prototype.memory_tile_shuffle.call; 


       // TODO perform a for loop from index 0 to the length of memory_array 
       for(var i = 0; i < memory_array.length; i++) 
       { 


        // TODO concatenate variable "output" to equal 
        //  '<div id="tile_' 
        output+='<div id = "tile_'; 
        output+=i; 
        output+='" onClick="memoryFlipTile(this,\''; 
        output+=memory_array[i]; 
        output+='\','+i+')"></div>'; 


       // TODO update the document object, element id called 'memory_board', innerHTML 
       //  so it is equal to the output variable 
       document.getElementById("memory_board").innerHTML=output; 
       } 
      } 

      // TODO write function Tile with parameters tile and val 
      function memoryFlipTile(tile, val,i) 
      { 
       // TODO check if the innerHTML of object tile is equal to "" and 
       //  the length of array memory_values is less than 2 
       if(document.getElementById('tile_'+i).innerHTML=="" && memory_values.length < 2) 
       { 
        // style settings for the background of the tile object 
        tile.style.background = '#FFF'; 

        // TODO set object tile innerHTML equal to the val parameter 
        document.getElementById("tile_"+i).innerHTML= val; 

        // TODO check if the length of array memory_values equals 0 
        if(memory_values.length == 0) 
        { 
         // TODO call function push on array memory_values passing 
         //  val as an argument 
         memory_values.push(val); 

         // TODO call function push on array memory_tile_ids passing 
         //  tile.id as an argument 
         memory_tile_ids.push(tile.id); 

        } 
        // TODO check if the length of array memory_values equals 1 
        else if(memory_values.length == 1) 
        { 
         // TODO call function push on array memory_values passing 
         //  val as an argument 
         memory_values(val); 


         // TODO call function push on array memory_tile_ids passing 
         //  tile.id as an argument 
         memory_tile_ids(tile.id); 

         // TODO check if memory_values index 0 equals memory_values index 1 
         if(memory_values[0] == memory_values[1]) 
         { 
          // TODO update the value of variable tiles_flipped to be increased by 2 
          tiles_flipped += 2; 

          // TODO clear array memory_values 
          memory_values = []; 

          // TODO clear array memory_tile_ids 
          memory_tile_ids = []; 

          // TODO check to see if the whole board is cleared by 
          //  comparing the number of tiles_flipped being equal to 
          //  the length of array memory_array 
          if(tiles_flipped == memory_array.length++) 
          { 
           alert("The board has been cleared and a new board is being generate"); 
           // TODO using an alert dialog box inform the user that 
           //  the board has been cleared and a new board is 
           //  being generated 

           // TODO update object document, id 'memory_board', innerHTML 
           //  to be equal to "" 
           document.getElementById("memory_board").innerHTML= ""; 

           // TODO call function newBoard 
           newBoard(); 

          } 
         } 
         // otherwise 
         else 
         { 
          // TODO write function flip2Back so it flips the turned over tiles to 
          //  no longer be visible 
          function flip2Back() 
          { 
           // Flip the 2 tiles back over 
           // TODO declare variable tile_1 set equal to object document, 
           //  element id memory_tile_ids, index 0 
           var tile_1 = document.getElementById("memory_tile_ids[0]"); 

           // TODO declare variable tile_1 set equal to object document, 
           //  element id memory_tile_ids, index 1 

           // style settings for tile_1 
           tile_1.style.background = 'pink'; 
           tile_1.innerHTML = ""; 

           // style settings for tile_2 
           tile_2.style.background = 'pink'; 
           tile_2.innerHTML = ""; 

           // TODO clear array memory_values 
           memory_values = []; 

           // TODO clear array memory_tile_ids 
           memory_tile_ids = []; 
          } 

          // TODO call function setTimeout passing arguments function flip2Back 
          //  and the value 700 
          setTimeout(flip2Back(),700); 

         } 
        } 
       } 
      } 
     newBoard(); 
     </script> 
0

Вы должны указать оператор document.getElementById("memory_board").innerHTML=output; из цикла for для размещения всех переменных div в выходной переменной .. и затем назначить его в innerhtml.

Смежные вопросы