将 UI HTML 与将填充您的列表的 Apps 脚本代码分开是一个好主意。所以首先,这里是如何分离这些位,availableTags
列表从应用程序脚本函数返回。(改编自之前对类似问题的回答。)
作为 Web 应用程序发布,这将产生一个带有自动完成功能的输入框,其中可用的标签已从应用程序脚本功能提供。我们在页面加载时调用该函数,如下所示:
google.script.run.withSuccessHandler(buildTagList)
.getAvailableTags();
代码.gs
function doGet() {
var template = HtmlService
.createTemplateFromFile('Autocomplete');
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
.setTitle('jQuery UI Autocomplete - Default functionality');
return htmlOutput;
}
function getAvailableTags() {
// In production code, get an array of options by
// reading a spreadsheet.
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
return( availableTags );
}
自动完成.html
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
<script>
// This code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(buildTagList)
.getAvailableTags();
});
function buildTagList(availableTags) {
$( "#tags" ).autocomplete({
source: availableTags
});
}
</script>
获取可用标签()
使用上述框架,您可以继续availableTags
从电子表格中填充列表,替换我们开始使用的固定数组。像这样的东西:
function getAvailableTags() {
var ss = SpreadsheetApp.openById("0Avt7ejriwlxudGZfV2xJUGJZLXktm2RhQU1uRUgtaXc");
var s = ss.getSheetByName("Database");
var data = s.getDataRange().getValues();
var headers = 1; // number of header rows to skip at top
var tagColumn = 2; // column # (0-based) containing tag
var availableTags = [];
for (var row=headers; row < data.length; row++) {
availableTags.push(data[row][tagColumn]);
}
return( availableTags );
}