【问题标题】:using newPosition() with Google Document将 newPosition() 与 Google 文档一起使用
【发布时间】:2014-05-16 19:32:11
【问题描述】:

document.newPosition(element,offest) 有问题。根据 API 规范,https://developers.google.com/apps-script/reference/document/document#newPosition(Element,Integer)

将包含新位置的元素;这必须是 文本元素或像段落这样的容器元素

我已经尝试使用 .getText 和 .editAsText 来获取 Text 元素:

  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 行是“var position=... 行。

使用 t2 (getText),我得到:

找不到方法 newPosition(string,number)。 (第 32 行,文件 “测试代码”)

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

【问题讨论】:

    标签: google-apps-script google-docs


    【解决方案1】:

    从文档看来,您的方法应该可以工作,但如您所知,它会引发错误。根据您的文档的外观,您还有其他几个选项可供选择。

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

    var d=DocumentApp.getActiveDocument();
    var body = d.getBody();
    var ix = 2;
    
    // this will get the position of the 2nd element in body container
    var position = d.newPosition(body,ix);
    

    选项二可能是从正文中获取子元素:

    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 元素。我想要做的是添加一个正则表达式搜索,所以我事先不知道 ix 指向哪个元素(段落)。
    • 那行不通。显然,Body 元素没有 Text 的偏移量:子索引 (205) 必须小于或等于子元素的数量 (28)。 (第 30 行,文件“testcode”)关闭
    • 用偏移整数进行实验以查看元素在正文中的布局方式。使用 1 或 2 查看光标的位置。如果您只有一个孩子(段落),那么超过 1 个将引发该错误。
    • 据我所知,Body 的元素是段落和表格单元格,至少在我正在使用的文档中是这样。现在,我可以在 Body 中对孩子使用循环,但我真的不想这样做,除非我必须这样做。就像我刚开始时所说的那样,它真的应该以某种方式在 Text 元素上工作,你不觉得吗?
    • 同意。我不知道为什么没有。神秘的“服务器”错误也无济于事。我会说这是一个错误。我认为我发布的最后一个 hacky 解决方案应该能让你到达那里。相当于说。 body.getChild(0).getChild(0) 这似乎也有效。
    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多