Reputation: 101
I'm currently working on a Greasemonkey script, that allows to add users to an ignore list which will block their comments from being rendered.
I store their userID via "GM_setValue". Everything is working just fine but I have problems to render the "Manage your ban-list" part of my script to pardon a user.
The codeblock I have troubles with:
var banList = GM_listValues(); // Array of Usernames
var manageBans = $("#content_content"); //The <div> I want to render the Banlist in.
manageBans.append("<h4>Manage ignorelist</h4>");
for (var i=0; i < banList.length; i++) {
var currentUser = banList[i];
manageBans.append($('<b>'+currentUser+'</b><a href ="javascript:void(null)"><img src="/redaktion/style/delete.png" width="16" height="16" alt="unblock_user"></a></br>').click(function(){ unbanUser(currentUser)}));
}
var unbanUser = function(name) {
GM_deleteValue(name);
};
So basically this is working fine, all banned users are rendered in a list and I can click to unban. But once I click at any user to call "unbanUser", the last user in the list gets unbanned and not the one I clicked at.
I guess the variable "currentUser" is always the last name on the list, I kinda wanted it to be a fix link for each user after the for-loop is finished. It's quite a trivial task but I don't find a proper solution.
Do you have a hint for me? Greets
Upvotes: 0
Views: 351
Reputation: 349142
At the end of the loop, currentUser
keeps getting overwritten on each iteration. Inside the click
function, you're referring to currentUser
, which equals the last definition of currentUser
.
To fix it, make use of closures:
function doSomething(currentUser) {
manageBans.append($('<b>'+currentUser+'</b><a href="javascript:void(null)"><img src="/redaktion/style/delete.png" width="16" height="16" alt="unblock_user"></a></br>').click(function(){
unbanUser(currentUser)
}));
}
for (var i=0; i < banList.length; i++) {
doSomething(banList[i]);
}
Upvotes: 1