0
現有的JavaScript元素我能做些什麼: 我有對象的數組,當用戶點擊一個名字,圖像會出現,當用戶點擊該圖像中點擊的次數將會呈現。替換爲另一個
我不能做什麼: 當另一名用戶點擊,現有的圖像和點擊數應更換爲最近點擊一個。你能幫我實現嗎?上的所有圖像無,然後顯示:
var myArray = [];
myArray[0]= {name: "Mel", img : "img/ml.jpg", clicks : 0};
myArray[1]= {name: "Ang", img : "img/ma.jpg", clicks : 0};
myArray[2]= {name: "Cam", img : "img/mk.jpg", clicks : 0};
myArray[3]= {name: "Val", img : "img/vs.jpg", clicks : 0};
myArray[4]= {name: "Gab", img : "img/ga.jpg", clicks : 0};
let elemName=[];
let elemImg=[];
let elemClick=[];
for (let i = 0; i < myArray.length; i++) { //create elements
elemName[i] = document.createElement("h2");
elemName[i].textContent = myArray[i].name;
elemImg[i] = document.createElement("img");
elemImg[i].src = myArray[i].img;
elemClick[i] = document.createElement("h3");
elemClick[i].textContent = myArray[i].clicks;
elemImg[i].onclick=function(){ //count clicks
myArray[i].clicks++;
elemClick[i].textContent = myArray[i].clicks;
};
document.body.appendChild(elemName[i]); //Show names
elemName[i].onclick=function(){ //When a name is clicked, display image and number of clicks, replacing the existing one
//????????????????
document.body.appendChild(elemImg[i]);
document.body.appendChild(elemClick[i]);
};
我想你會過得更好使用的replaceChild() – Alec