Google chrome extension 循环创建多个上下文菜单

Google chrome extension 循环创建多个上下文菜单,google-chrome-extension,contextmenu,Google Chrome Extension,Contextmenu,我有一段代码: for (game in settings_object.games) { chrome.contextMenus.create({ "title": "Add thread("+request.thread+") to game: "+game, "contexts":["page"], "onclick": functi

我有一段代码:

        for (game in settings_object.games)
        {   
            chrome.contextMenus.create({
                "title": "Add thread("+request.thread+") to game: "+game,
                "contexts":["page"],
                "onclick": function () {addThreadToGame(game,request.thread)}
            });

        }
生成一个上下文菜单,如:

  • 向游戏添加线程(1234):游戏一的ID
  • 将线程(1234)添加到游戏:游戏二的ID
  • 将线程(1234)添加到游戏:游戏三的ID
其目的是当用户单击“将线程(1234)添加到游戏:游戏一的ID”时,然后添加线程名称(“游戏一的ID”,“1234”)执行。。。不幸的是,addThreadToGame似乎总是作为addThreadToGame(“游戏三的ID”,“1234”)触发,因为传递给函数的值始终是它在运行时而不是菜单生成时的最后一个值。。。我遗漏了什么?

找到了答案:


在修改了我在

中找到的代码后,这个答案似乎有我需要的一半答案:
      for (game in settings_object.games)
      {   
          chrome.contextMenus.create({
              "title": "Add thread("+request.thread+") to game: "+game,
              "contexts":["page"],
              "onclick": (function(element) {
                      return function(info, tab) {
                          addThreadToGame(element,request.thread)
                      }
                  })(game)

          });
      }