【问题标题】:google apps script html select options loaded from spreadsheet data谷歌应用程序脚本 html 选择从电子表格数据加载的选项
【发布时间】:2015-07-30 12:51:47
【问题描述】:

Google 应用脚本、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>

【问题讨论】:

    标签: javascript jquery html google-apps-script


    【解决方案1】:

    要通过 id 在 jQuery 中引用您的选择列表,选择元素需要一个 id 属性 &lt;select id="optionList" name="optionList"&gt;。要将选项添加到选项列表,可以使用以下语法:list.append(new Option(countries[i],countries[i])); 其中第一个值是名称,第二个是值。

    您的 Google 脚本代码看起来不错,但您可以在 return 语句之前添加 Logger.log(countries); 以验证您返回的是预期结果。在您的 Google 脚本编辑器中,您可以通过单击运行 ->(函数名称)来测试函数,而不是单击查看 -> 日志来查看日志。最好先分别测试您的 Google Script 代码和 HTML 代码,然后再尝试将它们一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多