代码存储来自表单的数据并将其显示在列表中,当我单击随机时,它应显示数组中的随机值但不显示,它显示[对象对象]并且随机值不应重复
<form >
First Name<input id = "name1" required/>
Last Name <input id ="name2" required/>
City <input id ="city" required/>
</form>
<button onclick="getResult()" >SUBMIT</button>
<button onclick="getData()">Random</button>
<br><br>
<p id="store"></p>
<br>
Random Data:<output id="info"/>
<h3>Student Data </h3>
<output id="out"/>
<script>
var arr=[];
function getResult(){
var name1 = document.getElementById('name1').value;
var name2 =document.getElementById('name2').value;
var city = document.getElementById('city').value;
var students={
firstName:name1,lastName:name2,cityName:city
}
arr.push(students);
var k='';
for(var g=0;g<arr.length;g++)
k=k+" <li>"+eval(g+1)+'.'+arr[g].firstName+" "+arr[g].lastName+" "+arr[g].cityName+" </li>";
document.getElementById('out').innerHTML = k;
document.getElementById('name1').value="";
document.getElementById('name2').value="";
document.getElementById('city').value="";
document.getElementById('store').innerHTML='Number of students = ' +arr.length +'';
}
function getData(){
var rand = arr[Math.floor(Math.random() * arr.length)];
var el=document.getElementById('info')
el.innerHTML=rand;
}
</script>
答案 0 :(得分:0)
以下是否解决:
var arr=[];
var arrForRnd = [];
function getResult(){
var name1 = document.getElementById('name1').value;
var name2 =document.getElementById('name2').value;
var city = document.getElementById('city').value;
var students={
firstName:name1,lastName:name2,cityName:city
}
arr.push(students);
arrForRnd.push(students);
var k='';
for(var g=0;g<arr.length;g++)
k=k+createLi(g, arr[g]);
document.getElementById('out').innerHTML = k;
document.getElementById('name1').value="";
document.getElementById('name2').value="";
document.getElementById('city').value="";
document.getElementById('store').innerHTML='Number of students = ' +arr.length +'';
}
function createLi(g, studentInformation) {
return " <li>"+eval(g+1)+'.'+studentInformation.firstName+" "+studentInformation.lastName+" "+studentInformation.cityName+" </li>";
}
function getData(){
if(arr.length == 0){
return;
}
if(arrForRnd.length == 0){
for(loop = 0 ; loop < arr.length; loop++) {
arrForRnd.push(arr[loop]);
}
}
var rand = Math.floor(Math.random() * arrForRnd.length);
var el=document.getElementById('info');
el.innerHTML=createLi(rand, arrForRnd[rand]);
arrForRnd.splice(rand, 1);
}
&#13;
<form >
First Name<input id = "name1" required/>
Last Name <input id ="name2" required/>
City <input id ="city" required/>
</form>
<button onclick="getResult()" >SUBMIT</button>
<button onclick="getData()">Random</button>
<br><br>
<p id="store"></p>
<br>
Random Data:<span id="info"></span>
<h3>Student Data </h3>
<span id="out"></span>
&#13;
答案 1 :(得分:0)
您收到object
,因为您已将object
推入数组,并且您从object
返回array
。因此,您需要从object
获取属性并在div
中显示它们。
function getData(){
var rand = arr[Math.floor(Math.random() * arr.length)];
var el=document.getElementById('info')
el.innerHTML=rand.firstName;
}