【问题标题】:Included script in HTML file does not run in Google Apps Script HTMLServiceHTML 文件中包含的脚本不在 Google Apps Script HTMLService 中运行
【发布时间】:2016-03-11 19:53:09
【问题描述】:

我正在加载一个模板化的 HTML 文件,并且可以使用下面代码中显示的函数加载其他 HTML。我试图让包含的函数在脚本标签中运行。这是 Google Sheet 脚本中的 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 jquery google-apps-script google-apps


    【解决方案1】:

    您的问题是由于加载 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");
    }
    

    【讨论】:

    • 就是这样!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2017-10-27
    相关资源
    最近更新 更多