首页 > 解决方案 > Google Doc 标头中的 setAttributes 失败 - setAttibutes 不是函数

问题描述

我想在 google 文档标题中设置字体大小,但我收到错误“setAttributes 不是函数”。我无法真正理解标题的结构(似乎),关于在哪里设置属性。

      var style = {};
      style[DocumentApp.Attribute.FONT_SIZE] = 16;
      style[DocumentApp.Attribute.BOLD] = true;
      var range = this.Doc.getHeader(
      range.setText(text)
      var m = range.getNumChildren();
      for (var i =0; i<m;i++){
        var cld = range.getChild(i);
        var ct = cld.getText();
        var cat = cld.getAttributes();
        cld.setAttibutes(style);
      }

在上面的代码中,我可以在标题中设置文本,并且可以在第一个子元素“ct”中看到文本,但我无法设置属性。cld.getAttributes() 返回空值,所以我认为属性设置在更高的元素上。我只是不知道是哪个。

标签: google-apps-scriptheaderattributesgoogle-docs

解决方案


问题:

  • getChild返回元素,而不是Text,因此您需要更改cldText通过asText然后使用getText()
  • 至于setAttributes功能,我没有遇到您遇到的问题,它只是工作,所以我不知道为什么它会出错。

你可以试试这个吗?

代码:

function updateHeader() {
  var doc = DocumentApp.getActiveDocument(); 
  var range = doc.getHeader();

  var text = "this is the new header";
  var style = {};
  style[DocumentApp.Attribute.FONT_SIZE] = 16;
  style[DocumentApp.Attribute.BOLD] = true;

  var m = range.getNumChildren();
  for (var i = 0; i < m; i++){
    var cld = range.getChild(i);
    var ct = cld.asText().getText();    // get text value
    var cat = cld.getAttributes();      // get attributes
    Logger.log(ct);                     // print old text
    Logger.log(cat);                    // print old attributes
    
    cld.asText().setText(text);         // set text as header value
    cld.setAttributes(style);           // set attributes
    Logger.log(cld.asText().getText()); // print new text
    Logger.log(cld.getAttributes());    // print new attributes
  }
}

样本:

样本

输出:

输出

日志:

日志

笔记:

  • 我放置setText在循环内,向您展示更新文本和属性值之前和之后的差异。

推荐阅读