javascript - HTML 文件中包含的脚本无法在 Google Apps 脚本 HTMLService 中运行

标签 javascript jquery google-apps-script google-apps

我正在加载一个模板化 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/

相关文章:

javascript - 谷歌地图 v3 : How to change the map style based on zoom level?

javascript - 添加关闭按钮灯箱

jquery - if(this.id.match(/^None_+\d+_+\d+$/)) 中的错误是什么

Javascript 传播运算符替代

php - 请帮我获取 $randomQ 和 $matchinA,然后在输入 $matchinA 时刷新 jQuery?

jquery - 如何防止 Bootstrap css 类覆盖我的自定义 css 类

javascript - 在 Google Apps 脚本中访问多个参数值

javascript - 用于闪烁一系列单元格的 Google 电子表格脚本

google-apps-script - 使用谷歌脚本在谷歌驱动器中合并同名文件夹

javascript - 调用/应用严格函数与非严格函数时的不同类型 'this'