Reputation: 976
I am trying to assign an onclick event to a dynamically created panel element:
for(var c = 0; c < data.length; c++) {
var user = data[c];
document.querySelector('#userList').innerHTML += '<li class="user" id="button-login-' + c + '"><img src="user.png" /><span>' + user.username + '</span></li>';
document.querySelector('#button-login-' + c).onclick = function() {
self.port.emit('button', {
'action': 'login',
'data': {
'username': user.username
}
});
};
}
But it seems that the first onclick events being overwritten by the last one... Any help?
In the new code i tried this:
for(var c = 0; c < data.length; c++) {
user = data[c];
document.querySelector('#userList').innerHTML += '<li class="user" id="button-login-' + c + '"><img src="user.png" /><span>' + user.username + '</span></li>';
document.querySelector('#button-login-' + c).onclick = function() {
self.port.emit('button', {
'action': 'login',
'data': {
'username': user.username
}
});
};
}
and this:
for(var c = 0; c < data.length; c++) {
let user = data[c];
document.querySelector('#userList').innerHTML += '<li class="user" id="button-login-' + c + '"><img src="user.png" /><span>' + user.username + '</span></li>';
document.querySelector('#button-login-' + c).onclick = function() {
self.port.emit('button', {
'action': 'login',
'data': {
'username': user.username
}
});
};
}
the buttons don't work...
Upvotes: 1
Views: 230
Reputation: 1263
This is happening because of the way closures work in Javascript, not something specific to sdk or extensions.
See "Creating closures in loops: A common mistake" for a general solution to your problem.
For a simpler solution change
var user = data[c];
to
let user = data[c];
Upvotes: 2