Google Apps脚本:如何在Google文档中查找listItem对象并向其中插入项目? [英] Google Apps Script: How to find a listItem object in a google document and insert a item to it?
问题描述
在文档示例之后,我正在尝试创建一个函数来搜索google文档中的数字列表,如果找到了该函数,则向该列表添加一个新项目.但是我收到以下错误消息:Cannot find method setListId(string). (line 21, file "test")
,或者,如果我更改第21行的内容(将elementContent
替换为newElement
),则会收到消息:Preparing for execution...
,并且什么也没有发生.如何解决?
Following the documentation sample, I'm trying to create a function that searchs for a numerated list in a google document and, if finds it, adds a new item to that list. But I get this error: Cannot find method setListId(string). (line 21, file "test")
or, if I change line 21 content (replacing elementContent
for newElement
), I get the message: Preparing for execution...
and nothing happens. How to fix it?
这是我的代码:
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = "1R2c3vo9oOOjjlDR_n5L6Tf9yb-luzt4IxpHwwZoTeLE";
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
var listId = child.getListId();
var newElement = body.appendListItem(elementContent);
newElement.setListId(newElement);
Logger.log("child = " + child);
}
}
}
推荐答案
在我发表评论之后,我尝试使用您的脚本来查看发生了什么,然后在下面提出了该代码...
Following my comment, I tried to play with your script to see what happened and I came up with that code below...
我并不是说它可以解决您的问题和/或是实现所需目标的最佳方法,但至少可以使结果达到预期效果.
I'm not saying it solves your issue and/or is the best way to achieve what you want but at least it gives a result that works as expected.
请考虑将其视为新游乐场",并继续对其进行试验以使其变得更好;-)
Please consider it as a "new playground" and keep experimenting on it to make it better ;-)
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = DocumentApp.getActiveDocument().getId();
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
var childIndex = 0;
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
while(child.getType() == DocumentApp.ElementType.LIST_ITEM){
child = targetDoc.getChild(i)
childIndex = body.getChildIndex(child);
Logger.log(childIndex)
i++
}
child = targetDoc.getChild(i-2)
var listId = child.getListId();
Logger.log(childIndex)
var newElement = child.getParent().insertListItem(childIndex, elementContent);
newElement.setListId(child);
break;
}
}
}
这篇关于Google Apps脚本:如何在Google文档中查找listItem对象并向其中插入项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!