开发者

Passing values from Greasemonkey sandbox into anonymous functions

This is my first question, probably very silly indeed :)

I have a selection of values in an array, returned from GM_listValues().

As I loop over the collection, I want to dynamically create buttons that call a function to delete the stored value, and reload the page.

deleteB.addEventListener("click", function() {deleteTrip(names[i]);pageSelect();}, false);

Above is the line I am using to attach the 开发者_高级运维event to the button (deleteB). However, when I press the button, javascript tries to access the array of listValues (names) with the count variable (i). Naturally, this will not exist, as the loop is now done, and names is not global anyway.

What I want to know is if there is a way to copy the string value of names[i] while I am creating the function in the button, so as to not need a reference to names[i] in the code.

I know this is probably a really simple answer, but its got me stumped, this is some of my first work with javascript.

Thanks in advance.


Use a closure to remember the value;

function createDeleteFunc(name) {
  return function(){deleteTrip(name);pageSelect();}
}

for() {
...
deleteB.addEventListener("click", createDeleteFunc(names[i]), false);
...
}


The problem is that all functions you create reference the same i variable. When they are called, they try to delete names[i], but i is now equal to names.length so it doesn't work.

The solution is to make a separate reference to names[i] for each function. This is usually done with a closure (à-la Paul's answer)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜