列出几个"GM_listValues",调用一个函数以删除自己 [英] Make List of several "GM_listValues", calling a function to remove themselves
问题描述
我目前正在使用Greasemonkey脚本,该脚本允许将用户添加到忽略列表,这将阻止其注释的呈现.
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.
我通过"GM_setValue"存储其用户ID.一切正常,但是我在渲染脚本的管理您的禁止列表"部分时遇到问题,请原谅用户.
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.
我遇到麻烦的代码块:
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);
};
因此,基本上这可以正常工作,所有被禁止的用户都显示在列表中,我可以单击以取消禁止.但是,一旦我单击任何一个用户来调用"unbanUser",列表中的最后一个用户就会被禁止,而不是我单击的那个用户.
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.
我猜变量"currentUser"始终是列表上的姓,我有点希望它成为for循环完成后每个用户的固定链接. 这是一项微不足道的任务,但我找不到合适的解决方案.
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
推荐答案
在循环结束时,currentUser
每次迭代都会被覆盖.在click
函数内部,您引用的是currentUser
,它等于currentUser
的最后一个定义.
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]);
}
这篇关于列出几个"GM_listValues",调用一个函数以删除自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!