我将添加一个联系人列表,并根据 lname 的第一个字符将它们放入div中。如果div不存在,它将动态创建。我想显示点击名称的联系信息。在以下实现中,mc1 = null
功能无法显示联系信息。
showMe( )
答案 0 :(得分:1)
<script>
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 person = {
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length - 1]; //take the last pushed object from the array
var id = contacts.length - 1;
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if (!document.getElementById(lastNameFirstChar + "_holder"))
{
document.getElementById("mydiv").innerHTML += "<div id='" + lastNameFirstChar + "_holder' class='holder'><span>" + lastNameFirstChar + "</span></br></div>";
}
//document.getElementById(lastNameFirstChar + "_holder").innerHML += currPerson.fname+" "+currPerson.lname + "<br/>";
document.getElementById(lastNameFirstChar + "_holder").innerHTML += "<span onclick='showMe(" + id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";
}
function showMe(id)
{
//alert(id);
var person = contacts[id]; /* currently corresponds to array index, could be a property lookup with underscore or whatever */
var contactInfo = person.fname + " " + person.lname + "</br> " + person.email + "</br>" + person.phone;
mydiv.innerHTML = "<div>" + contactInfo + "</div></br>";
}
</script>
答案 1 :(得分:0)
当你调用showMe()函数时,你应该通过currPerson.id发送该人的id 但是当你定义var person时,你没有给它id属性。 你有这个
var person = {
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
像这样做
var person = {
id: contacts.length,// note this extra parameter
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
现在打电话
"<span onclick='showMe(" + currPerson.id + ")'>"
currentPerson.id将不再是未定义的。
其次当你拨打这一行时
target.innerHTML = "<div>" + contactInfo + "</div></br>";
您还没有定义变量&#34; target&#34;。
在上一行
之前添加此行var target= document.getElementById("mydiv")
其中&#34; myDiv&#34;是您在html标记中定义的内容的ID
<div id="mydiv">