【问题标题】:How do you create a button that will display a random result from an array in javascript?如何创建一个按钮来显示 javascript 中数组的随机结果?
【发布时间】:2015-06-16 23:28:55
【问题描述】:

我一直在尝试创建一个按钮,该按钮将从数组中获取随机名称,并将其显示在 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>

【问题讨论】:

  • 你实际上并没有显示结果 var postmessage= 只是将所需的结果分配给新变量。 return 立即退出函数。
  • 为什么您的postmessage() 函数以return 语句开头?这意味着该函数中的任何其他代码都不会执行。将return 语句放在函数的末尾。而且,一旦您致电postmessage(),您就必须对结果进行处理。

标签: javascript arrays button random onclick


【解决方案1】:

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;
};
<input type="button" value="Get Recruit" onclick="postmessage();" />
<div id="recruit"></div>

【讨论】:

  • 非常感谢!我尝试使用 document.getElementById 的东西,但没有结合使用 textContent 。在这个网站上搜索了几个小时,现在我觉得很愚蠢。有点JS新手,哈哈。无论如何,再次感谢!
猜你喜欢
  • 2021-08-02
  • 2017-01-12
  • 2023-03-24
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 2013-12-18
  • 2021-04-25
  • 1970-01-01
相关资源
最近更新 更多