为雇主开展一个相当简单的项目。我需要一份调查表,提交后会将答案转储到电子表格中。我正在使用 Google Apps 脚本开发一个独立的应用程序。项目管理层决定不使用 Google 表单。
我遇到的问题是检索单选按钮值。有很多单选按钮问题,我需要能够迭代它们以获得它们的值。
UI是通过GAS的UiApp服务完成的:
function doGet(e){
var app = UiApp.createApplication();
// set up the form
var form = app.createFormPanel();
var flow = app.createFlowPanel();
form.add(flow);
app.add(form);
// create the radio button groups (they are all Likert scales).
// I've written a function that creates a single group (see below)
for (var i=0; i<24; i++){
likertScale(i, flow);
};
flow.add(app.createSubmitButton('Submit')
return app;
}
我的 likertScale() 函数用于创建单选按钮组:
function likertScale(name, flow) {
// the 'name' argument allows me to pass in the var i from the
// for loop above to give each radio button group a unique name
// the 'flow' argument allows me to pass in the var flow that
// I created when setting up the form
var app = UiApp.getActiveApplication();
// create the N/A option, assign the group's name, give the button a label
// and a value
flow.add(app.createRadioButton('item'+name, 'N/A').setFormValue('NA'));
for (var j=1; j<6; j++) {
// create the 5-point Likert scale; assign the group's name to each button,
// use j to give each a label and a value
flow.add(app.createRadioButton('item'+name,j).setFormValue(j);
}
return app;
}
为了测试检索值的前提,我将文本包含值的标签添加到应用程序中。函数的相关部分:
function doPost(e) {
var app = UiApp.getActiveApplication();
for (var i=0; i<24; i++){
var radio = 'item'+i;
// I've previously set the name of each radio button group
// as 'item#', where # is a number 0-23.
app.add(app.createLabel().setText('You selected ' + e.parameter.radio));
// The idea is that each iteration recreates the name of a radio
// button, then uses that name to inform e.parameter.radio
};
return app;
}
真正让我困惑的是,虽然上面的代码重复了 24 次“您选择了未定义”,但下面的代码完全有效:
function doPost(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel().setText('You selected ' + e.parameter.item0
return app;
}
看来只要我不尝试任何循环并且我手动编码整个事情,一切都很好。
对此有什么见解吗?
最佳答案
您不能以这种方式引用变量“radio”,它将被解释为名为“radio”的属性尝试:
app.add(app.createLabel().setText('You selected ' + e.parameter[radio]));
在此处查看有关访问对象属性的方法的详细信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties
关于javascript - 在 Google Apps 脚本中迭代单选按钮值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303201/