使用 OfficeJS 在 word 中的内容控件中附加 onDelete 事件处理程序

Attaching onDelete event handler in a content control in word using OfficeJS

我在word中有内容控制。现在我希望在删除特定内容控件时执行特定操作。经过一些谷歌搜索后,我发现有一个名为 onDelete 的事件可以用于相同的目的。但是,我不太明白如何附加此事件处理程序。有人可以举例说明我们如何附加此侦听器的代码吗?

Word 中的事件处理与 Excel 中的事件处理相同。例如,您将处理程序附加到 worksheet.onChanged 事件,如下所示:

Excel.run(function (context) {
  var worksheet = context.workbook.worksheets.getItem("Sample");
  worksheet.onChanged.add(handleChange);

  return context.sync()
      .then(function () {
          console.log("Event handler successfully registered for onChanged event in the worksheet.");
      });
}).catch(errorHandlerFunction);

同样,在 Word 中,您获得对内容控件的引用并向 ContentControl.onDeleted 事件添加处理程序,如下所示:

Word.run(function (context) {
  var myContentControl = context.document.contentControls.getFirst();
  myContentControl.onDeleted.add(handleDeletion);

  return context.sync()
      .then(function () {
          console.log("Event handler successfully registered for onDeleted event in the document.");
      });
}).catch(errorHandlerFunction);

您还删除了 Word 事件中的处理程序,就像在 Excel 中删除它们一样。有关详细信息,请参阅 Excel add-in events