【发布时间】:2016-09-01 21:04:13
【问题描述】:
更新:不同之处在于我不是要创建一个列表,而是要创建一个可以单击并生成随机名称的按钮
目标:单击一个按钮并从数组中随机生成一个名称。我试图能够单击按钮并一次随机显示一个名称,而没有重复的名称。到目前为止,我已经能够随机选择一个名称,但名称仍然重复。如何更改我的代码以避免重复名称?
$( ".next").click(function() {
$(".intro").hide()
var people = ["Andrew", "Adam", "Seth", "Mattos", "Eric"];
for(i=0;i<1;i++){
var randomPosition = Math.floor(Math.random() * people.length);
var selected = people.splice(randomPosition,1);
console.log(selected)
$('#person').text(selected)
if ($('#person').text() === "Mattos"){
$("#selectedPerson").text("Mattos")
}
if ($('#person').text() === "Andrew"){
$("#selectedPerson").text("Andrew")
}
if ($('#person').text() === "Eric"){
$("#selectedPerson").text("Eric")
}
if ($('#person').text() === "Seth"){
$("#selectedPerson").text("Seth")
}
if ($('#person').text() === "Adam"){
$("#selectedPerson").text("Adam")
}
}
});
【问题讨论】:
-
为什么是
ifs ?为什么不使用相同的selectedvar 来设置#selectedPerson字段的text()? -
还尝试使用按钮而不是列表。
-
有什么区别?
-
为什么你有一个只执行1次的
for()循环?
标签: javascript jquery html arrays random