我正在为一所学校构建一个容器绑定的谷歌应用程序脚本。学校要求每个书面项目都有“学校标题”。学校使用积木 AG 作为句号。我的目标是会有一个菜单“School Heading”,打开后会有子菜单“A Block”、“B Block”、“C Block”,并且在每个子菜单中每个班级都有一个选项,其中将该类的标题插入到文档的标题中
这是我的代码:
var BLOCKS = "abcdefg";
var CLASSES = ["English", "History", "Science", "Writing", "Latin", "Math", "Study Skills"];
var FUNCTION_NAMES;
var global = {};
init();
/**
* The onOpen function runs automatically when the Google Docs document is
* opened. Use it to add custom menus to Google Docs that allow the user to run
* custom scripts. For more information, please consult the following two
* resources.
*
* Extending Google Docs developer guide:
* https://developers.google.com/apps-script/guides/docs
*
* Document service reference documentation:
* https://developers.google.com/apps-script/reference/document/
*/
function onOpen() {
init();
// Add a menu with some items, some separators, and a sub-menu.
var menu = DocumentApp.getUi().createMenu('School Heading')
for(var i = 0; i < BLOCKS.length; i++){
block = BLOCKS[i];
Logger.log("Block: " + block)
menu = menu.addSubMenu(DocumentApp.getUi().createMenu(block + " Block")
.addItem('English', 'eng' + block)
.addItem('History', 'his' + block)
.addItem('Science', 'sci' + block)
.addItem('Writing', 'wri' + block)
.addItem('Latin', 'lat' + block)
.addItem('Math', 'mat' + block)
.addItem('Study Skills', 'stu' + block));
defineFunctions(block, this);
}
menu.addToUi();
}
function getFunc(class,block){
return function(){
createHeading(class,block);
}
}
function defineFunctions(block, global){
Logger.log(FUNCTION_NAMES)
for(var i = 0; i < FUNCTION_NAMES.length; i++){
var funcName = FUNCTION_NAMES[i] + block;
eval("function " + funcName + " () { createHeading('"+ CLASSES[i] + "', '" + block + "'); }");
}
}
function createHeading(class, block){
var header = DocumentApp.getActiveDocument().getHeader();
if(!header){
header = DocumentApp.getActiveDocument().addHeader();
}
header.insertParagraph(0, "Name\n{class}, Block {block}".replace("{class}", class).replace("{block}", block)).setAlignment(DocumentApp.HorizontalAlignment.RIGHT);
}
function init(){
if(!Array.isArray(BLOCKS)){
BLOCKS = BLOCKS.toUpperCase().split("");
}
if(!Array.isArray(CLASSES)){
CLASSES = CLASSES.split("\n");
}
if(!Array.isArray(FUNCTION_NAMES) || FUNCTION_NAMES.length !== CLASSES.length){
FUNCTION_NAMES = [];
for(var i = 0; i < CLASSES.length; i++){
FUNCTION_NAMES.push(CLASSES[i].toLowerCase().substring(0,3));
}
}
}
当我选择School Heading > A Block > English我得到'Script function not found engA'
我的问题是,为什么 eval 不起作用,我是否可以将匿名函数传递给 Menu.addItem?