【发布时间】: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