谷歌应用程序脚本、javascript 等的新手......
尝试在电子表格中创建侧边栏,其中包含从其中一张工作表中的列填充的 html 选择对象。
我尝试使用在 this post 中找到的代码,但是加载 html 时加载选项的函数似乎没有执行。知道我做错了什么吗?
code.gs 中的代码:
function onOpen(e) {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('USD Conversion')
.addItem('Convert Dollars to Foreign Currency', 'showSidebar')
.addToUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "Load rates from CSV file", functionName: "importFromCSV"}];
var addCountriesMenuEntries = [{name: "Add Countries", functionName: "addCountries"}];
var conversionEntries = [{name: "Convert Dollars for Foreign Currency", functionName: "showSidebar"}];
}
/**
* Opens a sidebar in the document containing the add-on's user interface.
*/
function showSidebar() {
var template = HtmlService
.createTemplateFromFile('Sidebar')
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('USD Conversion')
.setWidth(400);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showSidebar(htmlOutput);
}
function getListOptions() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CountryCodes");
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("P2:P"+lastRow);
var countries = myRange.getValues();
return( countries );
}
Sidebar.html 中的代码:
<div class="labels">
<p>Destination Country:</p>
</div>
<div>
<select name="optionList">
<option>Loading...</option>
</select>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function () {
google.script.run.withSuccessHandler(buildOptionList)
.getListOptions();
});
function buildOptionList(countries) {
var list = $('#optionList');
list.empty();
for (var i = 0; i < countries.length; i++) {
list.append(countries[i]);
}
}
</script>
最佳答案
要通过 id 在 jQuery 中引用您的选择列表,select 元素需要一个 id 属性 <select id="optionList" name="optionList">
.要将选项添加到选项列表,您可以使用以下语法:list.append(new Option(countries[i],countries[i]));
其中第一个值是名称,第二个是值。
您的 Google Script 代码看起来不错,但您可以添加 Logger.log(countries);
就在你的返回声明之前,以验证你正在返回预期的结果。在您的 Google Script 编辑器中,您可以通过单击运行 ->(函数名称)而不是单击查看 -> 日志来查看日志来测试函数。最好先分别测试您的 Google Script 代码和 HTML 代码,然后再尝试一起使用它们。
关于javascript - 谷歌应用程序脚本 html 选择从电子表格数据加载的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31724307/