我有一个涉及CSS和JavaScript的随机名称生成器代码。就目前的代码而言,我可以输入任何名称(不论性别),单击“生成”按钮,然后会弹出一个随机的名字和姓氏。唯一的问题是,我希望能够为男性,女性和男女通用名称创建单独的按钮。
我尝试为名称和女性名称创建单独的div id,复制javascript并将代码部分更改为“femalename”和“malename”,但是这破坏了格式,因此当我按下生成按钮之一时,两个div都会生成一个名称。
<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Random name generator</title>
<meta charset='utf-8' />
<style type='text/css'>
#name {
color : #444;
font : bold 51px times, Times New Roman, times-roman, georgia, serif;
letter-spacing : -2px;
line-height : 44px;
text-align : center;
text-transform: uppercase;
}
#refresh {
font : normal 11px Gill Sans, Verdana;
letter-spacing : 2px;
line-height : 14px;
text-align : center;
text-transform : uppercase;
}
a {
color : #666;
}
a:hover {
color : #999;
}
</style>
</head>
<body>
<script type='text/javascript'>
first = ['abbie ', 'abby ', 'abu ', 'alec ', 'alek ', 'aleksander ', 'alex ', 'alexander ', 'aaron ', 'adam ', 'andrew ', 'anthony ', 'archer ', 'arthur ', 'austin '];
last = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];
name = "";
length = Math.floor(Math.random()) + 1;
for (i = 0; i < length; i++)
name += (first[Math.floor(Math.random()*first.length)]
+ last[Math.floor(Math.random()*last.length)]);
name = name.charAt(0) + name.slice(1);
document.write("<p id='name'>" + name + "</p>");
</script>
<p id="refresh">
<a href='#' onclick='window.location.reload()'>generate a new one</a>
</p>
</body>
</html>
最佳答案
我将更改函数以接受HTML中的性别,以及在加载时运行该函数。
这也是带有“任何性别”选项的示例:https://codepen.io/kboedges/pen/qeXmqK?editors=1111
const maleFirst = ["abu", "alec", "alek"];
const femaleFirst = ["abbie", "abby", "katie", "leah"];
const last = ["williamson", "davidson", "edwards", "ingram", "olsen"];
// Function
function generateName(gender) {
const randomLast = last[Math.floor(Math.random() * last.length)];
const randomMaleName = `${maleFirst[Math.floor(Math.random() * maleFirst.length)]} ${randomLast}`;
const randomFemaleName = `${femaleFirst[Math.floor(Math.random() * femaleFirst.length)]} ${randomLast}`;
// Insert into HTML
const p = document.getElementById('name');
p.innerHTML = gender === 'female' ? randomFemaleName : randomMaleName;
}
// On first run
generateName('male');
#name {
color: #444;
font: bold 51px times, Times New Roman, times-roman, georgia, serif;
letter-spacing: -2px;
line-height: 44px;
text-align: center;
text-transform: uppercase;
}
#refresh {
font: normal 11px Gill Sans, Verdana;
letter-spacing: 2px;
line-height: 14px;
text-align: center;
text-transform: uppercase;
}
a {
color: #666;
}
a:hover {
color: #999;
}
<p id='name'></p>
<p id="refresh">Generate a...
<a href='#' onclick="generateName('female')">female name</a>
<a href='#' onclick="generateName('male')">male name</a>
</p>