从Google表格html模板运行时,经过测试的javascript无法正常工作

问题描述 投票:1回答:1

总体上我对脚本编写非常陌生,所以请多多包涵。

我正在Google表格上测试一些脚本,并运行HTML模板。

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

您将看到脚本按需运行。

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

在Google表格脚本中,以下功能用于运行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>

the actual result when code is run

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

javascript arrays google-sheets dropdown
1个回答
1
投票

在Apps脚本中,您可以使用scriptlets来实现此功能>

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

示例:

index.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>

Code.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内容之后将其从头移到正文。

[这允许您在使用Java脚本修改HTML内容之前,呈现HTML内容(基本上创建一个ID为” selectNumber”的元素,请参见Best Practices

© www.soinside.com 2019 - 2024. All rights reserved.