Word JS API。在运行时添加或删除段落时,body.paragraphs 集合不会更新

问题描述 投票:0回答:1

我在 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 中出现

如何获取更新的段落合集?

ms-word office-js office-addins word-addins word-web-addins
1个回答
0
投票

您好,您的代码不正确。 “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);
© www.soinside.com 2019 - 2024. All rights reserved.