javascript GAS:键:菜单的值数组

kknvjkwl  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(101)

所以我试图使用Google Apps脚本将一个key:value数组转换为菜单。我目前使用的是SpreadsheetApp,但希望将其用于其他应用程序。
我的问题是使用context_menu()方法在context_menu()中的m.addToUi()行上出现Exception: Custom menus must contain at least one item.错误
我已经使用simple_menu()测试了这个,以确保我理解它是如何工作的(它工作得很好),所以我不确定问题是什么。

var f = 'my_function'
var m_contex = {"Item1":f, "Item2":f, "SubMenu":{"subItem1":f, "subItem2":f}, "Item3":f}

function my_function(){
  Logger.log("triggered");
}

function cm_rec(ui, m, name, items){
  var sm = ui.createMenu(name);
  m.addSubMenu(sm);
  for(var key in items){
    if(typeof items[key] === "string"){
      Logger.log("adding " + key + " to "+name);
      sm.addItem(key, items[key]);
    }else{
      cm_rec(ui, sm, key, items[key]);
    }
  }
}
function context_menu(ui, title, items){
  var m = ui.createMenu(title);
  for(var key in items){
    if(typeof items[key] === "string"){
      Logger.log("adding " + key + " to "+title);
      m.addItem(key, items[key]);
    }else{
      cm_rec(ui, m, key, items[key]);
    }
  }
  m.addToUi();
}

function simple_submenu(ui, m, title){
  var sm = ui.createMenu(title);
  sm.addItem("SubItem1", 'my_function');
  sm.addItem("SubItem2", 'my_function');
  m.addSubMenu(sm);
}
function simple_menu(ui){
  var m = ui.createMenu("My Menu");
  m.addItem("Item1", 'my_function');
  m.addItem("Item2", 'my_function');
  simple_submenu(ui, m, "SubMenu");
  m.addItem("Item3", 'my_function');
  m.addToUi();
}

function tester1(){ //runs the simple_menu
  var ui = SpreadsheetApp.getUi();
  Logger.log("Creating Simple Menu");
  simple_menu(ui);
}
function tester2(){ // runs the context_menu
  var ui = SpreadsheetApp.getUi();
  Logger.log(m_contex);
  context_menu(ui, "Custom Menu", m_contex);
}

tester2的输出是正确的,除了以下错误:

2:44:27 PM  Info    {Item3=my_function, Item1=my_function, SubMenu={subItem2=my_function, subItem1=my_function}, Item2=my_function}
2:44:27 PM  Info    adding Item1 to Custom Menu
2:44:27 PM  Info    adding Item2 to Custom Menu
2:44:27 PM  Info    adding subItem1 to SubMenu
2:44:27 PM  Info    adding subItem2 to SubMenu
2:44:27 PM  Info    adding Item3 to Custom Menu
ars1skjm

ars1skjm1#

在您的脚本中,我认为以下部分可能需要修改。

var sm = ui.createMenu(name);
m.addSubMenu(sm);

因为在这种情况下,sm是没有添加任何项目的,我想这可能是您现在发布Exception: Custom menus must contain at least one item.的原因,那么在这种情况下,下面的修改如何?

修改的脚本:

在该修改中,请如下修改函数cm_rec

function cm_rec(ui, m, name, items) {
  var sm = ui.createMenu(name);
  for (var key in items) {
    if (typeof items[key] === "string") {
      Logger.log("adding " + key + " to " + name);
      sm.addItem(key, items[key]);
    } else {
      cm_rec(ui, sm, key, items[key]);
    }
  }
  m.addSubMenu(sm); // This line was moved.
}

相关问题