无法从 Google 文档中清除页脚
Unable to clear footer from Google Document
当我 运行 下面的代码时,我收到一个 TypeError:
TypeError: Cannot call method "clear" of null. (line 3, file "Code")
来自行:footer.clear()
function insertFooterDate() {
var footer = DocumentApp.getActiveDocument().getFooter();
footer.clear(); // Line 3 - gets the footer & clears all data in footer.
//Get date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();
var hour = date.getHours()+1;
var minute = date.getMinutes()+1;
var filename = doc.getName();
footer.appendParagraph(day + '/' + month + '/' + year + ' ' + filename);
//adds date to footer with filename
}
为什么我的代码执行时会出现此错误?
如果 Google Docs 文件中没有页脚,则无法调用不存在的方法。 Apps 脚本文档服务为 add a footer 提供了一种方法,因此您应该决定是中止需要页脚的方法(如果还没有),还是创建一个。该决定将取决于您的方法应该做什么。
function doStuffWithFooter_(myGDoc) {
if (!myGDoc) return;
const footer = myGDoc.getFooter();
if (!footer) {
console.warn("Document '" + myGDoc.getId() + "' had no footer.");
return;
}
... // code that should only run if the doc already had a footer
}
function addDateToFooter_(myGDoc) {
if (!myGDoc) return;
var footer = myGDoc.getFooter();
if (!footer) {
// no footer, so create one.
footer = myGDoc.addFooter();
console.log("Created footer for document '" + myGDoc.getId() + "'.");
}
... // do stuff with footer, because we made sure one exists.
}
当我 运行 下面的代码时,我收到一个 TypeError:
TypeError: Cannot call method "clear" of null. (line 3, file "Code")
来自行:footer.clear()
function insertFooterDate() {
var footer = DocumentApp.getActiveDocument().getFooter();
footer.clear(); // Line 3 - gets the footer & clears all data in footer.
//Get date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();
var hour = date.getHours()+1;
var minute = date.getMinutes()+1;
var filename = doc.getName();
footer.appendParagraph(day + '/' + month + '/' + year + ' ' + filename);
//adds date to footer with filename
}
为什么我的代码执行时会出现此错误?
如果 Google Docs 文件中没有页脚,则无法调用不存在的方法。 Apps 脚本文档服务为 add a footer 提供了一种方法,因此您应该决定是中止需要页脚的方法(如果还没有),还是创建一个。该决定将取决于您的方法应该做什么。
function doStuffWithFooter_(myGDoc) {
if (!myGDoc) return;
const footer = myGDoc.getFooter();
if (!footer) {
console.warn("Document '" + myGDoc.getId() + "' had no footer.");
return;
}
... // code that should only run if the doc already had a footer
}
function addDateToFooter_(myGDoc) {
if (!myGDoc) return;
var footer = myGDoc.getFooter();
if (!footer) {
// no footer, so create one.
footer = myGDoc.addFooter();
console.log("Created footer for document '" + myGDoc.getId() + "'.");
}
... // do stuff with footer, because we made sure one exists.
}