简体   繁体   中英

Why does not this code work?

This code should work.. But it doesn't and I get an error message that says:

Uncaught TypeError: Cannot set property 'innerHTML' of null

It is not the first time I've gotten this error and I still don't understand it...

HTML:

<!DOCTYPE html>
<html>
<head>
<title></title>

<link rel="stylesheet" type="text/css" href="mycss.css">
<script src="myjavascript2.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

</head>

<body>

<button onclick="myFunction()">Play</button>
<p id="test"></p>



</body>
</html>

javascript:

var things = ['rock','paper','scissors'];

function myFunction() {

var i = Math.floor(Math.random()*things.length));
document.getElementById("test"+(i+1)).innerHTML=things[i];
}

它看起来像你有任何元素与像test1test2等ids。

The element referenced by your code does not exist in the DOM:

document.getElementById("test"+(i+1))

You have in your HTML:

<p id="test"></p>

Your code is looking for "test3"

If you want the single element to change the text, have this as your JavaScript:

document.getElementById("test").innerHTML=things[i];

If you want it go go into multiple elements, then in your HTML replace <p id="test"></p> with:

<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>

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