如何创建一个按钮,在javascript中显示数组的随机结果?

时间:2015-06-16 23:28:56

标签: javascript arrays button random onclick

我一直在尝试创建一个从数组中随机取名的按钮,并将其显示在html页面上。已经尝试了很长时间才能使这个工作,没有结果。是什么给了什么?

同样,如果您知道答案,我怎样才能创建另一个显示多个结果的按钮,而不仅仅是一个?

<!doctype html>
<html>
<head>
<script>
function postmessage(){
 return "Your new recruit is " + firstnames;

  var firstnames = ["John", "Jacob", "Eric", "Conroy", "Vincent", "Laurence", "Jack", "Harry",    "Richard", "Michael", "Kevin", "Daniel", "Cody", "Brody", "Chase", "Cash", "Norman", "Trevor", "Todd", "Ellis", "Quentin", "Zachary", "Bruce", "Sam", "Horace", "George", "Tom", "Tim", "Wallace", "Walter", "Alex", "Alan", "Sean", "Seamus", "Dudley", "Duke", "Damian", "Nash", "Horton", "Robert", "Mitchell", ];
  var firstnames = firstnames[Math.floor(Math.random() * firstnames.length)];
  var postmessage = "Your new recruit is " + firstnames;
 };
</script>

<meta charset="UTF-8">
<title>Untitled Document</title>
</head>

<body>
<input type="button" value="Get Recruit" onClick="postmessage();"/>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
function postmessage() {
  var firstnames = ["John", "Jacob", "Eric", "Conroy", "Vincent", "Laurence", "Jack", "Harry", "Richard", "Michael", "Kevin", "Daniel", "Cody", "Brody", "Chase", "Cash", "Norman", "Trevor", "Todd", "Ellis", "Quentin", "Zachary", "Bruce", "Sam", "Horace", "George", "Tom", "Tim", "Wallace", "Walter", "Alex", "Alan", "Sean", "Seamus", "Dudley", "Duke", "Damian", "Nash", "Horton", "Robert", "Mitchell", ];
  var firstname = firstnames[Math.floor(Math.random() * firstnames.length)];
  document.getElementById("recruit").textContent = "Your new recruit is " + firstname;
};
&#13;
<input type="button" value="Get Recruit" onclick="postmessage();" />
<div id="recruit"></div>
&#13;
&#13;
&#13;