简体   繁体   中英

I want to print a random string on my current page

I'm new at javascript, but I want a random string. this string should be printed on my current page. I already have:

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <script type="text/javascript">
var strings = ['aaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'ccccccccccccccccccccccccccccccccccccccc'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.getElementById('randomString').innerHTML = randomString;
</script>
</head>
<body>
<div id="randomString"></div>
</body>

according to JSFiddle, this should work, but it doesn't. what should I change?

It does not work because your javascript is executed before the #randomString div exists. So, you need to either move your javascript after the #randomString div in the code, or use onLoad attribute of the to execute the function when the document is ready, which means that you would need to wrap your current code in a function.

You try to access the div with the id randomString before it exists in the DOM. Move the <script> to the bottom (somewhere after the div ) and it'll work.

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div id="randomString"></div>
  <script type="text/javascript">
var strings = ['aaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'ccccccccccccccccccccccccccccccccccccccc'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.getElementById('randomString').innerHTML = randomString;
</script>
</body>
</html>

btw, your code missed the </html>

You may try this :

window.onload=function(){

var strings = ['aaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',    'ccccccccccccccccccccccccccccccccccccccc'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.getElementById('randomString').innerHTML = randomString;

 }

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