Sha*_*dow 4 google-apps-script
我需要创建一个谷歌应用程序脚本,它将在活动文档中插入一些字符串。我需要稍后知道用户是否使用了文档上的脚本并更改了已插入的文本。
是否可以为我添加的字符串标记或插入自定义属性/属性?
例如,而不是添加
<b>Custom Text</b>
Run Code Online (Sandbox Code Playgroud)
可以插入这个吗?
<p CustomAttribute=Cust1>Custom Text</p>
Run Code Online (Sandbox Code Playgroud)
另外,如何在文档中搜索我的自定义属性?
小智 7
您可以使用NamedRanges实现这种类型的效果。基本上,该策略是:
这是此类策略的粗略实现:
function testing() {
// Add a new paragraph within a Named Range
var named = addTextWithNamedRange('This is my added text', 'RangeLabel01');
// NamedRanges can share the same names, but the IDs are unique,
// so use IDs to easily reference specific NamedRanges
var namedId = named.getId();
// Now save this ID to a data structure, along with any other information
// about it you need to record
// Later, when you need to reference that text/paragraph/element,
// use the ID to find it, and make any changes you need:
accessNamedRange(namedId);
}
function addTextWithNamedRange(str, name) {
// Add a new paragraph to end of doc
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.appendParagraph(str);
// Creates a NamedRange that includes the new paragraph
// Return the created Named Range
var rangeBuilder = doc.newRange();
rangeBuilder.addElement(text);
return doc.addNamedRange(name, rangeBuilder.build());
}
function accessNamedRange(rangeId) {
// Determine if a NamedRange with this ID exists
// If it does, log information about it and the Paragraph
// elements it includes
var doc = DocumentApp.getActiveDocument();
var named = doc.getNamedRangeById(rangeId);
if (named) {
var rangeElements = named.getRange().getRangeElements();
for(var r in rangeElements) {
var text = rangeElements[r].getElement().asParagraph().getText();
// Just logging here, but could potentially edit or
// otherwise manipulate the text
Logger.log('Found NamedRange ' + named.getName() +
' (id='+rangeId+') --> ' + text);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1335 次 |
最近记录: |