指定菜单功能的参数 [英] Specify parameters for menu functions

查看:173
本文介绍了指定菜单功能的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Google Apps脚本中的代码段,用于在 Google Docs/中添加菜单表格/表格.如Menu#addItem方法中所述,它调用menuItem2函数,但是该片段未包含有关要在函数调用中添加参数时如何调用addItem的示例,或者这是不可能的吗? /p>

This is a snippet in the Google Apps Script for adding a menu in Google Docs/Forms/Sheets. As stated in the Menu#addItem method it calls the menuItem2 function, but the snippet didn't include a sample on how to call the addItem when you want to add parameters in function call, or is this not possible?

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Custom Menu')
    .addItem('First item', 'menuItem1')
    .addSeparator()
    .addSubMenu(ui.createMenu('Sub-menu')
      .addItem('Second item', 'menuItem2'))
    .addToUi();
}

function menuItem2() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('You clicked the second menu item!');
}

function menuItem2(PARAMETER_HERE) {
  // codes    
}

推荐答案

您不能向菜单调用的函数添加参数.

You can't add parameters to functions called by a menu.

一个简单的解决方法是将参数存储在其他位置(例如,在scriptProperties中),如果参数未定义,则读取这些参数.

A simple workaround is to store parameters elsewhere (in scriptProperties for example) and read these parameters if parameter is undefined.

function menuItem2(PARAMETER) {
  // if PARAMETER is undefined then read default parameter in scriptProperties
  // codes    
}

在此配置中,您可以使用正常"参数从脚本的其他位置调用menuItem2函数,它将按预期进行处理.

In this configuration you can call the menuItem2 function from elsewhere in the script using a "normal" parameter and it will be handled as expected.

这篇关于指定菜单功能的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆