var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
for(i=0;i<contacts.length;i++){
document.getElementById("mydiv").innerHTML += contacts[i].fname+" "+contacts[i].lname;
}
}
I want to display only the new array elements. In the above code, every time a new element enters the array all elements are displayed. How can I avoid repetition? I think using the DOM is an option. I'm stuck trying to implement this.
最佳答案
您可以这样做,仅将array
的最后一个元素
添加到innerHTML
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
document.getElementById("mydiv").innerHTML += contacts[contacts.length-1].fname+" "+contacts[contacts.length-1].lname;
}
关于javascript - 在输入数组元素时显示 html 页面中的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798728/