google-apps-script - 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() 返回空值,所以我认为属性设置在更高的元素上。我只是不知道是哪个。
解决方案
问题:
getChild
返回元素,而不是Text
,因此您需要更改cld
为Text
通过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
在循环内,向您展示更新文本和属性值之前和之后的差异。
推荐阅读
- react-native - 如果他们在一段时间内处于空闲或不活动状态,则对本机注销用户做出反应
- regex - 如何使用正则表达式模式拆分此模式中的句子
- regex - 如何根据字符位置查找具有条件的行?
- office365 - 是否可以将成员添加到对其 SharePoint 网站具有读取权限的 office 365 组
- postgresql - 在字符变化字段上使用分组时查询慢
- c++ - 前后增量
- javascript - 将状态数组值转换为键值对
- r - 带有 networkD3 的桑基图 - 创建链接
- java - Antlr 语法无法提供所需的 AST
- python - 将响应类型更改为 str、bytes 或 os.Pathlike