我正在加载一个模板化 HTML 文件,并且可以使用下面代码中所示的函数加载其他 HTML。我正在尝试让包含的函数在脚本标签中运行。这是 Google 表格脚本中的 HTMLService。
在Code.gs中我有
function doGet() {
var template = HtmlService.createTemplateFromFile("template")
.evaluate()
.setTitle('My Title')
.setHeight(700)
.setWidth(1000)
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return template
// SpreadsheetApp.getActive().show(template);
};
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
};
function includeRaw(filename) {
return HtmlService.createTemplateFromFile(filename).getRawContent();
}
在我的template.html中我有
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('mystylesheet'); ?>
<?!= includeRaw('Billets_JS'); ?>
</head>
<body> ...(more body)
<select id="optionListYear" onchange="setFormList()">
<option>Option 1</option>
<option>Option 2</option>
</select>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
function setFormList() {
alert("In setFormList");
MyNEwFunction();
}
</script>
我还尝试了 JavaScript 文件的直接 include() 函数
Billets_JS 有这个:
<script>
alert("Script included!");
// This code in this function runs when the page is loaded IF in the initial html file.
$(function() {
alert("In the intial function");
});
function MyNewFunction() {
alert("In My New Function");
}
</script>
我可以获得仅需要加载脚本(“Billets_JS”)的 HTML 文件。如果我有一个警报();在此包含文件中的任何函数之外的行(例如所示的函数),该行将运行。所以我收到一个警告框,上面写着“包含脚本!”但不是“在初始功能中”的那个。
不过,我似乎无法以这种方式调用 MyNewFunction() 。我已经使用了 Code.gs 中的两个 Include 函数
有没有办法加载将运行的脚本而不将其全部放入初始加载的文件中?只需将函数移动到最初加载的文件即可,但我宁愿将它们隔离。
最佳答案
您的问题是由于加载JavaScript脚本的顺序造成的;由于 Billets_JS
依赖于 jQuery,因此它应该在之后加载。
简单地移动:
<?!= includeRaw('Billets_JS'); ?>
出现在:
之后<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
如果您想主动解决此问题,可以在 Billets_JS
脚本顶部检查 jQuery 的可用性,如下所示:
if (typeof jQuery == 'undefined') {
alert("No jQuery");
}
关于javascript - HTML 文件中包含的脚本无法在 Google Apps 脚本 HTMLService 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35948772/