Google apps script 将newPosition()与Google文档一起使用

Google apps script 将newPosition()与Google文档一起使用,google-apps-script,google-docs,Google Apps Script,Google Docs,我对document.newPosition(元素,offest)有问题。根据API规范 将包含新位置的元素;这必须是一个 文本元素或类似段落的容器元素 我尝试了.getText和.editAsText以获取文本元素: var d=DocumentApp.getActiveDocument(); var t1=d.getBody().editAsText(); var t2=d.getBody().getText(); 然后 var position = d.newPositi

我对document.newPosition(元素,offest)有问题。根据API规范

将包含新位置的元素;这必须是一个 文本元素或类似段落的容器元素

我尝试了.getText和.editAsText以获取文本元素:

  var d=DocumentApp.getActiveDocument();
  var t1=d.getBody().editAsText();
  var t2=d.getBody().getText();
然后

  var position = d.newPosition(t1,ix);
  var position = d.newPosition(t2,ix);
其中,ix是一个绝对在文本大小内的整数

使用t1(editAsText),我得到:

很抱歉,发生了服务器错误。请稍等,然后重试。 (第32行,文件“testcode”)

其中第32行是“变量位置=…行”

使用t2(getText),我得到:

找不到方法newPosition(字符串,数字)。(第32行,文件 “测试代码”)


有人知道如何使用文本元素获取新位置吗?

从文档中可以看出,您的方法应该有效,但正如您所知,它会抛出错误。您确实可以根据文档的外观选择其他几个选项

请记住,
newPosition()
创建了一个相对于特定元素(文本元素或容器元素)的位置。由于将整个正文作为文本元素会引发错误,因此只需将正文作为容器元素使用即可

选项二可以是从主体中获取子元素:

var child = body.getChild(2);

// if the 2nd child is a paragraph, the new position will be at the end of the paragraph
// any number greater than one would actually reference the position of the next 
// child and throw an error.
var position = d.newPosition(child, 1)

它看起来像是要把光标
x
空格放在一个特定的元素中。在这种情况下,你需要得到那个特定的元素。可能是正文中段落中的文本元素

var body = d.getBody();
var parTwo = body.getChild(2);
var childTwo = parTwo.getChild(0);
var position = d.newPosition(childTwo, ix);

谢谢。我想我会试试Body元素。我想做的是添加一个regex搜索,这样我事先就不知道ix指向哪个元素(段落)。这不起作用。显然,Body元素没有文本的偏移量:子索引(205)必须小于或等于子元素的数量(28)。(第30行,文件“testcode“)使用偏移整数进行实验,以查看元素在主体中的布局。使用1或2查看光标的位置。如果您只有一个子项(段落),然后不止1个会抛出该错误。根据我所能确定的,Body的元素是段落和表格单元格,至少在我正在处理的文档中是这样。现在,我可以在Body中使用子元素循环,但我真的不想这样做,除非我必须这样做。就像我开始时说的,它确实应该在文本元素上工作哦,你不这么认为吗?同意。我不知道为什么会这样。而神秘的“服务器”错误也没有帮助。我认为这是一个bug。我认为我发布的上一个黑客解决方案应该能让你达到目的。这相当于说。
body.getChild(0)。getChild(0)
,这似乎也能奏效。
var body = d.getBody();
var parTwo = body.getChild(2);
var childTwo = parTwo.getChild(0);
var position = d.newPosition(childTwo, ix);