问题描述
在代码的底部是我遇到困难的地方。我的全局变量contacts在匿名函数中被返回为null
constructor(name,last,email,pic,color){
this.name = name;
this.last = last;
this.email = email;
this.pic = pic;
this.color = color;
}
updateContact(){
var contactDiv = document.getElementById('name')
contactDiv.innerHTML = ""
contactDiv.innerHTML += `<h1>${this.name} ${this.last}</h1>`;
document.getElementById('contactEmail').innerHTML = `<a href="mailto:${this.email}">${this.email}</a>`
//removed the .png from the contact1 & contact2 so the below would work with .png
// i wanted the Image Drop Down to display just the dwarf's name (ex: not "bashful.png")
document.getElementById('contactImg').src = `images/${this.pic}.png`;
}
}
这是创建全局变量的地方
var contact1 = new Contacts("SNow","White","swhite@castle.com","sNowwhite","black")
var contact2 = new Contacts("Dopy","Dwarf","ddwarf@cottage.com","dopy","black")
var contacts = [contact1,contact2]
// calls the newly created function (below) so the initial names show up
displayContact()
//create onclick button that grabs the data and drives the function
document.getElementById("addContact").addEventListener("click",newCharGrab)
//console.log(mybtn)
//create a function that grabs the data for the new Character
function newCharGrab(){
var name = document.getElementById("fname").value
var last = document.getElementById("lname").value
var email = document.getElementById("email").value
var imgSrc = document.getElementById("imgSrc").value
var color = "black"
var newContact = new Contacts(name,imgSrc,color)
//updates the array with the new contact made
contacts.push(newContact)
//this calls the display function to refresh the contact list displayed
displayContact()
//alert("here")
}
console.log(contacts)
//display the name of all the contacts we currently have
// modified this because i was having issues recalling it after my newCharGrab function
// Now it is called right after the initial contacts are made and then once again after activated by the click
function displayContact(){
var strContacts = "<ul>"
for(var i = 0; i < contacts.length; i++){
strContacts += `<li value=${i} name="${i}"style='color:${contacts[i].color}'>${contacts[i].name} ${contacts[i].last} </li>`
console.log(i.color)
}
strContacts += "</ul>"
document.getElementById('contactList').innerHTML = strContacts
}
以上工作正常
//made with the video,this uses an anonomous function to listen for when the name
// of a contact is clicked it displays the information held in the constructor for
// that contact.
document.getElementById('contactList').addEventListener('click',function(e){
console.log(contacts[e.target.value])
console.log(e.target.innerHTML)
document.getElementById('contacts').style.color = "black" //**This comes back as null**
contacts[e.target.value].color = "purple"
displayContact()
contacts[e.target.value].updateContact();
})```
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)