javascript - 从 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>
任何帮助将不胜感激。谢谢!
解决方案
在 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”的元素),请参阅最佳实践。
推荐阅读
- php - Laravel 字符串数据,右截断:1406 Data too long for column
- jquery - 在我当前的日期选择器代码中禁用特定日期的最快方法?
- c++ - c++类成员函数指针在类中不能正常工作
- node.js - 如何将变量分配给节点js中的sqlite查询的输出
- python - 如何编写python代码批量将json转换为html?
- php - 如何将字符串拆分为字母和数字组件?
- c# - C#不要在包含相同文本的列表中添加重复项
- docker - Docker compose 镜像升级
- arrays - 将字符串传递给另一个函数后如何打印字符串数组
- swift - 检测 SwiftUI 工作表何时被刷掉