我在 Scriptlab 中试验 API 时遇到了问题。我的脚本在文档中插入了一些段落,然后我想遍历文档中的所有段落并更改一些格式。但似乎
body.paragraphs
集合在 context.sync()
调用之间没有更新。
这里是示例代码:
async function run() {
await Word.run(async (context) => {
var pars = context.document.body.paragraphs.load("items");
await context.sync();
// Returns "1", as the document has only one empty paragraph
console.log(pars.items.length);
// Insert three new paragraphs. Now there are 4 in the document
["Cat", "Dog", "Mouse"].forEach(p => context.document.body.insertParagraph(p,"End"));
pars = context.document.body.paragraphs.load("items");
await context.sync();
//But I still get 1 in the console window!
console.log(pars.items.length);
//New paragraphs are unchanged when we iterate over them
pars.items.forEach(p => p.set({lineSpacing: 40, leftIndent: 10 }))
await context.sync();
})
}
此行为在 Word Online 中出现
如何获取更新的段落合集?
您好,您的代码不正确。 “pars”应该是paragraphcollection。你能试试这个代码吗:
const body = context.document.body;
body.clear();
["Cat", "Dog", "Mouse"].forEach(p => body.insertParagraph(p, "End"));
var pars = context.document.body.paragraphs;
pars.load();
await context.sync();
console.log(pars.items.length);