javascript - 在特定位置附加段落

标签 javascript google-app-engine google-apps-script google-docs

我需要能够将一串文本更改为 heading1 并稍后进行一些额外的格式化。现在 catch 这部分。这是我目前的示例代码。

function pocket() {
    // Try to get the current selection in the document. If this fails (e.g.,
    // because nothing is selected), show an alert and exit the function.
    var selection = DocumentApp.getActiveDocument().getSelection();
    var body = DocumentApp.getActiveDocument().getBody();
    if (!selection) {
        DocumentApp.getUi().alert('Cannot find a selection in the document.');
        return;
    }
    var selectedElements = selection.getSelectedElements();
    var selectedElement = selectedElements[0];
    var pocketelement = selectedElement.getElement().getText();
    body.appendParagraph(pocketelement).setHeading(DocumentApp.ParagraphHeading.HEADING1);
}

我需要它来删除原始字符串并将段落附加到原始字符串位置。不知道该怎么做。任何帮助将不胜感激!

最佳答案

body.appendParagraph() 方法将给定的段落(如 javascript)附加到正文的末尾。

您正在寻找 .insertParagraph(index, Paragraph)。要获取索引,请尝试 body.getChildIndex(paragraph)。请参阅下面的代码。

function pocket() {
  // Try to get the current selection in the document. If this fails (e.g.,
  // because nothing is selected), show an alert and exit the function.
  var doc = DocumentApp.getActiveDocument();
  var selection = doc.getSelection();
  var body = doc.getBody();
  if (!selection) {
      DocumentApp.getUi().alert('Cannot find a selection in the document.');
      return;
  }
  var selectedElements = selection.getSelectedElements();
  var selectedElement = selectedElements[0];
  //holds the paragraph
  var paragraph = selectedElement.getElement();
  //get the index of the paragraph in the body
  var paragraphIndex = body.getChildIndex(paragraph);
  //remove the paragraph from the document
  //to use the insertParagraph() method the paragraph to be inserted must be detached from the doc
  paragraph.removeFromParent();
  body.insertParagraph(paragraphIndex, paragraph).setHeading(DocumentApp.ParagraphHeading.HEADING1);
};

关于javascript - 在特定位置附加段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27516995/

相关文章:

javascript - 如何按值查找输入元素 ID?

javascript - 如何将 application/x-mpegURL 放入 videojs 的源中

javascript - 循环设置内部 HTML

python - 从Python客户端访问后端API

google-apps-script - 自定义 Google 电子表格/表格工具栏

javascript - knockout 可观察的访问属性

google-app-engine - Google App Engine 上的博客

node.js - 无法在谷歌应用引擎上部署我的 reactjs webpack 应用程序

javascript - 如何将变量名称附加到 .getSheetByName()

google-apps-script - wsdl soap 请求中多个元素的问题