Based on onClick function I want to get data for the particular user. What I tried to create a function getSelectedData and tried to called by passing current data as an argument.
But received only the last value of the array.
function getSelectedData(receiveData){
console.log(receiveData)
}
var card = document.getElementById('mainBody')
var x = ""
for(var i = 0; i <= user.length -1; i ){
var UserData = user[i]
x = x `
<div onclick="getSelectedData(UserData)">
<img src="${user[i].userImage}" alt="" />
<p >${user[i].userName}</p>
<p >${user[i].userCountry}</p>
<p >${user[i].userProfession}</p>
</div>` ;
}
card.innerHTML = x
CodePudding user response:
By the time getSelectedData
is actually called, the value in UserData
is the last value assigned to it.
If instead you had used
... onclick="getSelectedData(' UserData ')"...
each onclick
would have the value of UserData
at the time you were adding to x
.
CodePudding user response:
You are inserting a new user, similar to this innerHTML. This is an inappropriate way because it overrides all content. You may use this "appendChild" like this "card.appendChild"