我想制作一个脚本来跟踪按下按钮的次数。众所周知,javascript 缺乏对静态变量的支持,但这通常可以作为在目标函数外部定义变量的解决方法。
尽管如此,这对我来说在简单的谷歌脚本网络应用程序上不起作用。代码如下,它是模板 Web 应用程序的简单扩展。
谁知道如何实现这一点?
这是谷歌应用程序的代码:
// Script-as-app template.
function doGet() {
var app = UiApp.createApplication();
var button = app.createButton('Click Me');
app.add(button);
var label = app.createLabel('The button was clicked.')
.setId('statusLabel')
.setVisible(false);
app.add(label);
myClickHandler.counter = 0;
var handler = app.createServerHandler('myClickHandler');
handler.addCallbackElement(label);
button.addClickHandler(handler);
return app;
}
function myClickHandler(e) {
var app = UiApp.getActiveApplication();
var label = app.getElementById('statusLabel');
label.setVisible(true);
label.setText('Clicked ' + myClickHandler.counter + ' times.')
myClickHandler.counter++;
//app.close();
return app;
}
最佳答案
有几种可能的方法可以实现这一点,其中之一是使用隐藏的小部件来保存值。
function doGet(){
var app = UiApp.createApplication();
var button = app.createButton('Click Me');
app.add(button);
var counterValue = 0;
var label = app.createLabel('The button was clicked.')
.setId('statusLabel')
.setVisible(false);
var counter = app.createHidden('counter').setId('counter').setValue(counterValue)
app.add(label).add(counter);
var handler = app.createServerHandler('myClickHandler');
handler.addCallbackElement(counter);
button.addClickHandler(handler);
return app;
}
function myClickHandler(e) {
var app = UiApp.getActiveApplication();
var label = app.getElementById('statusLabel');
label.setVisible(true);
var counterValue = Number(e.parameter.counter)
var counter = app.getElementById('counter')
counterValue++;
counter.setValue(counterValue.toString())
label.setText('Clicked ' + counterValue + ' times.')
return app;
}
关于google-apps-script - 处理程序中是否可以有静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12751224/