【问题标题】:Move to last line of Google Document when it is opened打开 Google 文档时移至最后一行
【发布时间】:2019-04-30 12:13:04
【问题描述】:

我正在编写我的第一个 Google Apps 脚本,我的目标是在打开文档时自动将光标移动到文档的最后一行。到目前为止,我的函数如下所示:

function onOpen(e) {
  var doc = DocumentApp.getActiveDocument();
  var paragraph = doc.getBody().appendParagraph('');
  var position = doc.newPosition(paragraph.getChild(0), 2);
  doc.setCursor(position);
}

我的解决方案基于this documentation

此脚本与文档几乎完全匹配。但是当我打开文档时,什么也没有发生。

我可能做错了什么?

这是我第一次使用 Javascript

编辑:这与this question不同——我希望在打开文档时自动执行脚本。

在鲁本的建议下,我检查了视图 > 执行。果然,脚本失败并显示以下错误消息:

Child index (0) must be less than the number of child elements (0). at onOpen(Code:4)

【问题讨论】:

标签: javascript google-apps-script google-docs


【解决方案1】:

更新:

Child index (0) must be less than the number of child elements (0). at onOpen(Code:4)

上面的错误信息意味着附加的段落没有孩子

试试这个

function onOpen(){
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var numChildren = body.getNumChildren();
  var pos = doc.newPosition(body.getChild(numChildren - 1),0);
  doc.setCursor(pos);
}


onOpen 以有限的授权级别运行,这意味着除了创建菜单之外,onOpen 不能对用户界面进行更改。也许这会导致您的脚本无法按预期工作。可以肯定的是,单击 View > Executions 并查找错误。

【讨论】:

  • 更新后的答案有效!此外,运行 onOpen 命令似乎不是问题。
【解决方案2】:

以下代码将转到最后一个字符或最后一个孩子的第一个:

const onOpen = () => {
  const doc = DocumentApp.getActiveDocument()
  const body = doc.getBody()
  const kids = body.getNumChildren()
  const lastKid = body.getChild(kids - 1)
  let last = 0
  try {
    const lastPar = body.getChild(kids - 1).asParagraph()
    last = doc.newPosition(lastPar.getChild(0), lastPar.getText().length)
  } catch (e) {
    last = doc.newPosition(body.getChild(kids - 1), 0)    
  } finally {
    doc.setCursor(last)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2019-08-08
    • 2020-08-20
    相关资源
    最近更新 更多