看起来很麻烦,Lists 是由 ListItems 组成的,但似乎没有 List 对象。有一个 ListId,但它似乎没有任何实际功能,除了您可以拆分列表并继续数字。您似乎只能将 ListItem 添加到正文中,但似乎没有一种简单的方法可以获取 ListItem 的索引以便您可以在它之后追加。
我编写了一个函数,它将遍历正文中的所有项目以查找带有一些占位符文本的 ListItem 并返回其索引。
function findListItemWithText(text) {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var index = -1;
for (var i=0; i<body.getNumChildren(); i++) {
var child = body.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM) {
var listItem = child.asListItem();
if (listItem.getText() == text) {
index = i;
}
}
}
return index;
}
然后我编写了一个函数,将 ListItem 替换为数组中的元素:
function replaceListItem (placeholder, list) {
var index = findListItemWithText(placeholder);
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var listItem = body.getChild(index).asListItem();
// replace the text in the placeholder ListItem
listItem.setText(list[0]);
// append the rest of the list after the placeholder ListItem
for (var i=1; i<list.length; i++) {
body.insertListItem(index + i, list[i]);
}
}
然后您可以使用占位符和列表调用此函数,如果存在带有此文本的 ListItem,它将在该点附加 ListItems 列表。
replaceListItem("{{list}}", ["One", "Two", "Three"]);
它适用于编号列表和项目符号列表。如果有两个或更多占位符,它将只替换最后一个。
如果有人可以对此提出批评,我很想知道找到和操作给定元素的更有效方法,因为我的解决方案似乎比我预期的要多得多。