简体   繁体   中英

Cannot read property 'innerHTML' of null - Doesn't Seem to be DOM

I need a fresh set of eyes on this. I've looked around stackoverflow for the typical "Cannot read property 'innerHTML' of null" and it seems to be typically caused by the DOM element not being loaded before a script is called to make a change. However, my error is created after clicking on the element, so I figure it's there already.

The line number of the error is the if statement: if(document.getElementById('tile').innerHTML=="" && memory_values.length < 2 ) contained within the memoryFlipTile function.

I believe the error caused by the newBoard() function:

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

In particular, I believe I made a mistake within the for loop but I'm not entirely sure what. My hunch is that the elements using the onClick function have no values.

Here is the full code:

<!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>
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>

It looks like you're creating several tiles with IDs like tile_1 , tile_2 , etc., but then later trying to find something with the id of just tile . Nothing has the id of just tile so the lookup is failing. You need to getElementById of tile_x where x is the number of the tile you're looking for.

In your dom, you're passing in the object as this :

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

but in your memoryFlipTile function, you're using the string "tile" instead of the parameter tile that is being passed in. In the places we're you're currently looking up by the string "tile", you instead want to look by by the variable tile.id , as in:

document.getElementById(tile.id)

Here's a minimum reproduction: https://jsfiddle.net/orz89xwr/

You need to place document.getElementById("memory_board").innerHTML=output; statement out of the for loop for containing all div in output variable..and then assign it to innerhtml.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM