0

我试图让一个按钮多次触发(即多次点击),但它似乎不起作用。任何帮助将不胜感激。理论上它应该触发多次,但是当我在日志中检查它时它只会触发一次

function a 
{
...
 var addcolumnspanel = app.createHorizontalPanel().setId("addcolumnspanel");
  var addbuttonhandler = app.createServerHandler("addcolumn");
  var addbutton = app.createButton().setId("btnaddcolumn").setText("Add another column").addClickHandler(addbuttonhandler);  

...
return app;
}

function addcolumn()
{
...//Do some stuff
return app;
}

这是一个更精确的代码示例

//set global var
var counter = 1; 
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Set up the Menu bar 
function onOpen() {
//  Logger.clear();
  var menuEntries = [ {name: "demo", functionName: "myFunction"}];
  ss.addMenu("Demo", menuEntries);

}

function myFunction() {

  var myapp = UiApp.createApplication().setHeight(430).setWidth(800);;
  var button = myapp.createButton("Clicky");
  var myhandler = myapp.createServerHandler("secondfunction");
  var myhandler = button.addClickHandler(myhandler)
  myapp.add(button);
  ss.show(myapp);
}

function secondfunction()
{
  counter++;
   Logger.log(counter);

}
4

1 回答 1

0

好的。问题出在计数器变量上。您不能在 Apps 脚本中以这种方式使用全局变量。有关更多信息,请参阅此答案。您可以使用 ScriptProperties 或 CacheService 作为替代方案。

var ss = SpreadsheetApp.getActiveSpreadsheet();
//Set up the Menu bar 
function onOpen() {
//  Logger.clear();
  var menuEntries = [ {name: "demo", functionName: "myFunction"}];
  ss.addMenu("Demo", menuEntries);
  // Store your counter in CacheService as a string.
  CacheService.getPrivateCache().put('counter','1',3600); 
}

function myFunction() {

  var myapp = UiApp.createApplication().setHeight(430).setWidth(800);;
  var button = myapp.createButton("Clicky");
  var myhandler = myapp.createServerHandler("secondfunction");
  var myhandler = button.addClickHandler(myhandler)
  myapp.add(button);
  ss.show(myapp);
}

function secondfunction()
{
   var cache = CacheService.getPrivateCache();
   var counter = parseInt(cache.get('counter'));
   counter ++; 
   cache.put('counter', counter.toString());
   Logger.log(counter);

}
于 2013-05-15T04:46:25.033 回答