首页 > 解决方案 > 从 Google Sheets html 模板运行时,工作测试的 javascript 不起作用

问题描述

总的来说,我对脚本编写非常陌生,所以请多多包涵。

我正在谷歌表格上测试一些脚本,运行一个 HTML 模板。

我的部分脚本需要调用数组数据。我正在测试运行这个脚本:http: //jsfiddle.net/nExgJ/

您将看到脚本按需要运行。

但是,当从 Google 表格启动 HTML 模板时,即使使用相同的代码,也不会填充数字。

在 Google Sheets 脚本中,以下函数用于运行 HTML 模板:

  var htmlDlg = HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setWidth(500)
      .setHeight(150);
  SpreadsheetApp.getUi()
  .showModalDialog(htmlDlg, 'Select An Existing Client');
}

我还有一个 doGet 函数,如下所示:

function doGet() {
 var htmlOutput = template.evaluate()
                   .setSandboxMode(HtmlService.SandboxMode.NATIVE);
  return htmlOutput;
  return HtmlService.createHtmlOutputFromFile('index');
}

那么我的HTML表单中的代码如下:

<!DOCTYPE html>
<html>
  <head>
     <script>
    // Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}

    </script>
  </head>
  <body>
<form id="myForm">
  <select id="selectNumber">
    <option>Choose a number</option>
  </select>
</form>
  </body>
</html>

代码运行时的实际结果

任何帮助将不胜感激。谢谢!

标签: javascriptarraysgoogle-sheetsdropdown

解决方案


在 Apps Script 中,您可以使用scriptlet来实现此功能

scriptlet 的优点是您还可以将电子表格中的数据或变量中的数据合并Code.gs到您的选项中。

样本:

索引.html

<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
<form id="myForm">
  <select id="selectNumber">
    <option>Choose a number</option>
    <? var myArray = new Array("1", "2", "3", "4", "5");?>
    <? for (var i = 0; i < myArray.length; ++i) { ?>
     <option> <?=myArray[i]?> </option>
     <? } ?>
  </select>
</form>
  </body>
</html>

代码.gs

function myFunction() {
  var template = HtmlService.createTemplateFromFile('index');  
  var htmlDlg = template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setWidth(500)
  .setHeight(150);
  SpreadsheetApp.getUi()
  .showModalDialog(htmlDlg, 'Select An Existing Client');
}

更新:

如果您更喜欢使用您的脚本,则必须在其余 html 内容之后将其从头移动到正文。

这允许您在使用 Javascript 修改此 html 的内容之前呈现 HTML 内容(基本上创建一个 id 为“selectNumber”的元素),请参阅最佳实践


推荐阅读