经过工作测试的javascript在从Google Sheets html模板运行时不起作用



我对脚本编写很陌生,所以请耐心等待。

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

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

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

然而,当HTML模板从Google Sheets启动时,即使使用相同的代码,也不会填充数字。

在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>

代码运行时的实际结果

如有任何帮助,我们将不胜感激。谢谢

在应用程序脚本中,您可以使用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>

代码.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"的元素(,请参阅最佳实践。

最新更新