使用Javascript获取随机单词以显示页面加载

时间:2015-11-22 16:47:27

标签: javascript jquery random

我试图创建一个随机单词生成器,当您单击按钮时,会出现一个随机单词。 我设法让这个工作,但也希望在页面加载时出现一个随机单词(这样它不仅仅是一个空白页面)。

谢谢!

的Javascript

var randomStrings = [
    "hello 1",
    "hello 2",
    "hello 3", 
    "hello 4",
    "hello 5",
];



var randomDiv = document.getElementById("myRandomDiv");

document.getElementById("myButton").addEventListener("click", function() {
      randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
      newText = randomStrings[randomIndex];
      randomDiv.innerHTML = newText;
});

HTML

  <!doctype html>
  <html>

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brandomiser</title>
    <link href='https://fonts.googleapis.com/css?family=Martel:900' rel='stylesheet' type='text/css'>
    <link href="main.css" rel="stylesheet" type="text/css">
    <link href="/downloads/favicon.ico" />
  </head>

  <body>
  <div class="row">
    <div id="bar" class="col-12 col-t-12 col-d-12 col-b-12">
      <p id="brand">Brandomiser</p>
    </div>
  </div>

  <div class="row">
    <div class="col-12 col-t-12 col-d-12 col-b-12">
      <h1 id="myRandomDiv"></h1>
    </div>
  </div>

  <div class="row">
    <div id="buttonmiddle" class="col-12 col-t-12 col-d-12 col-b-12">
      <button type="button" id="myButton">Hit me.</button>
    </div>
  </div>
  <script src="thing.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  </body> 
  </html>       

2 个答案:

答案 0 :(得分:2)

你必须在页面加载时调用generate函数。

像这样改变你的JS代码

  var randomStrings = [
    "Endsleigh",
    "Colgate",
    "Shell",
    "Tesco",
    "Swatch",
    "Vanish",
  ];

  var randomDiv = document.getElementById("myRandomDiv");

  document.getElementById("myButton").addEventListener("click", generate);

  function generate() {
    randomIndex = Math.ceil((Math.random() * randomStrings.length - 1));
    newText = randomStrings[randomIndex];
    randomDiv.innerHTML = newText;
  }

  generate();

答案 1 :(得分:1)

试试这个:

var randomStrings = [
    "Endsleigh",
    "Colgate",
    "Shell",
    "Tesco",
    "Swatch",
    "Vanish"];

var randomDiv = document.getElementById("myRandomDiv");

document.getElementById("myButton").addEventListener("click", function () {
    var randomIndex = Math.ceil((Math.random() * 10) % randomStrings.length - 1);
    newText = randomStrings[randomIndex];
    randomDiv.innerHTML = newText;
});
<div class="row">
    <div id="bar" class="col-12 col-t-12 col-d-12 col-b-12">
        <p id="brand">Brandomiser</p>
    </div>
</div>
<div class="row">
    <div class="col-12 col-t-12 col-d-12 col-b-12">
         <h1 id="myRandomDiv"></h1>

         <h1 id="Brandomiser">Brandomiser</h1>

    </div>
</div>
<div class="row">
    <div id="buttonmiddle" class="col-12 col-t-12 col-d-12 col-b-12">
        <button type="button" id="myButton">Hit me.</button>
    </div>
</div>