识别 ListItems 的 Office JS 问题

Office JS issue with recognising ListItems

我正在尝试在文档末尾添加一个段落并避免将新添加的段落添加到列表中的可能性(如果文档以列表结尾)。

我有以下代码:

let paragraph = paragraphs.items[paragraphs.items.length - 1]
let p = paragraph.insertParagraph('', window.Word.InsertLocation.after)

if (paragraph.listItemOrNullObject) {
    p.detachFromList()
    p.leftIndent = 0
}

发生以下情况:如果存在 ListItem,则代码有效。如果不是,它会在 if 条件内中断,就像我写的 paragraph.listItem.

不应该这样用吗?

编辑 - 抛出错误:

name:"OfficeExtension.Error"
code:"GeneralException"
message:"GeneralException"
traceMessages:[] 0 items
innerError:null
▶debugInfo:{} 4 keys
    code:"GeneralException"
    message:"GeneralException"
    toString:function (){return JSON.stringify(this)}
    errorLocation:"Paragraph.detachFromList"

listItemOrNullObject 将 return 一个空对象,如果它不是 ListItem。从概念上讲,您 if 是在询问 "if this is a list item or it isn't a list item",这实际上也会 return 为真。

您试图从一个不存在的列表中分离出来失败了。我会看看 isListItem。这将明确告诉您该段落是否为 ListItem,因此您仅在实际上它是列表的一部分时才执行 p.detachFromList()

这里的问题是 *.isNullObject methods/properties 不是 return 一个普通的 js 'null' 对象,而是一个 NullObject(一种特殊的 null 框架类型)。

查看这段代码,我重写了它,我认为这是一种更有效的方式。对不起我的js,你可以把它移植到ts。

希望这对您有所帮助。

Word.run(function (context) {
        var  listI = context.document.body.paragraphs.getLast().listItemOrNullObject;
        context.load(listI);
        return context.sync()
            .then(function () {
                if (listI.isNullObject) { // check out how i am validating if its null.
                    console.log("there is no list at the end")
                }
                else {
                    context.document.body.paragraphs.getLast().detachFromList();
                    context.document.body.paragraphs.getLast().leftIndent = 0;
                    return context.sync();
                }

            })
    })