修改现有表单值 - GetChoices() 不工作
Modify existing form Values - GetChoices() not working
为什么“.getChoices()”不适用于现有列表项?
我有以下代码,它通过 ID 获取表单中的项目,我打算更新表单项目的值。但是,当使用 .getChoices() 方法时,它会失败并出现错误“TypeError:无法在对象项目中找到函数 getChoices。”
我抓取的项目是需要的列表项,创建列表项时然后抓取,它正常工作,如示例代码所示here.
我的代码如下:
function getWeekNumberFormItem() {
var form = FormApp.getActiveForm();
var item = form.getItemById(12345);//redacted for privacy, but the ID in here is correct.
var title = item.getTitle();
var itemType = item.getType();
Logger.log('Item Type: ' + itemType);
Logger.log('Item Title: ' + title);
var choices = item.getChoices();
Logger.log(choices);
}
为了证明它是一个列表项,我的日志输出是:
我是不是用错了,还是只能在 Apps 脚本创建项目时使用?相反,我将如何获得此列表项中的选择并使用新选项更新它们?我看到其他用户已经设法做到这一点,所以我相信这是可能的。
Item
是一个 接口 class,它提供了一些适用于所有表单项的方法。 "Interface objects are rarely useful on their own; instead, you usually want to call a method like Element.asParagraph() to cast the object back to a precise class."ref
因为.getChoices()
是属于ListItem
class, and does not appear in Item
, you need to cast your Item
to ListItem
using Item.asListItem()
的方法。
...
var itemType = item.getType();
if (itemType == FormApp.ItemType.LIST) {
var choices = item.asListItem().getChoices();
// ^^^^^^^^^^^^
}
else throw new Error( "Item is not a List." );
为什么“.getChoices()”不适用于现有列表项?
我有以下代码,它通过 ID 获取表单中的项目,我打算更新表单项目的值。但是,当使用 .getChoices() 方法时,它会失败并出现错误“TypeError:无法在对象项目中找到函数 getChoices。”
我抓取的项目是需要的列表项,创建列表项时然后抓取,它正常工作,如示例代码所示here.
我的代码如下:
function getWeekNumberFormItem() {
var form = FormApp.getActiveForm();
var item = form.getItemById(12345);//redacted for privacy, but the ID in here is correct.
var title = item.getTitle();
var itemType = item.getType();
Logger.log('Item Type: ' + itemType);
Logger.log('Item Title: ' + title);
var choices = item.getChoices();
Logger.log(choices);
}
为了证明它是一个列表项,我的日志输出是:
我是不是用错了,还是只能在 Apps 脚本创建项目时使用?相反,我将如何获得此列表项中的选择并使用新选项更新它们?我看到其他用户已经设法做到这一点,所以我相信这是可能的。
Item
是一个 接口 class,它提供了一些适用于所有表单项的方法。 "Interface objects are rarely useful on their own; instead, you usually want to call a method like Element.asParagraph() to cast the object back to a precise class."ref
因为.getChoices()
是属于ListItem
class, and does not appear in Item
, you need to cast your Item
to ListItem
using Item.asListItem()
的方法。
...
var itemType = item.getType();
if (itemType == FormApp.ItemType.LIST) {
var choices = item.asListItem().getChoices();
// ^^^^^^^^^^^^
}
else throw new Error( "Item is not a List." );