Make List of several “GM_listValues”, calling a function to remove themselves

有些话、适合烂在心里 提交于 2019-12-13 08:49:34

问题


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


回答1:


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]);
}


来源:https://stackoverflow.com/questions/10073870/make-list-of-several-gm-listvalues-calling-a-function-to-remove-themselves

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!