You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script弹窗开发求助:实现下拉框选值存入tempString

修正后的代码实现

Code.gs

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('自定义菜单')
    .addItem('运行测试函数', 'testFunction')
    .addToUi();
}

// 全局变量存储选中值
var tempString = "";

function testFunction() {
  // 获取Sheet1中A1:A4的名称数据,转换为一维数组
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var arrayOfNames = sheet.getRange(1, 1, 4).getDisplayValues().flat();
  
  tempString = arrayOfNames[0]; // 初始化tempString为第一个名称
  Browser.msgBox("弹窗选择前tempString的值:" + tempString);

  // 创建HTML模板并传入名称数组
  var template = HtmlService.createTemplateFromFile("file");
  template.arrayOfNames = arrayOfNames;
  var widget = template.evaluate().setWidth(300).setHeight(200);
  
  SpreadsheetApp.getUi().showModalDialog(widget, "选择名称");
}

// 接收前端传递的选中值,更新全局变量tempString
function updateTempString(selectedValue) {
  tempString = selectedValue;
  Browser.msgBox("弹窗选择后tempString的值:" + tempString);
}

file.html

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <style>
    body { padding: 20px; font-family: Arial, sans-serif; }
    select, button { padding: 8px; margin-top: 10px; }
  </style>
</head>
<body>
  <p>请选择匹配的名称:name3</p>
  <select id="names">
    <option selected disabled>选择一个名称</option>
    <? for(var i=0; i<arrayOfNames.length; i++) { ?>
      <option><?= arrayOfNames[i] ?></option>
    <? } ?>
  </select><br><br>
  <button type="button" onclick="submitSelection()">确定</button>

  <script>
    function submitSelection() {
      var selectedValue = document.getElementById("names").value;
      if(selectedValue) {
        // 调用后端函数更新tempString,成功后关闭弹窗
        google.script.run.withSuccessHandler(function() {
          google.script.host.close();
        }).updateTempString(selectedValue);
      } else {
        alert("请选择一个名称!");
      }
    }
  </script>
</body>
</html>

核心修改说明

  • HTML模板优化:
    • 移除无效的onload事件,直接用GAS模板语法循环生成下拉选项,避免无效的options数组定义
    • 添加submitSelection()函数,获取选中值后通过google.script.run与后端交互
  • 后端逻辑修正:
    • 将getDisplayValues()返回的二维数组转为一维数组,避免下拉选项显示异常
    • 使用模板传递数据替代无效的widget.options赋值,实现名称数组向HTML的传递
    • 新增updateTempString()函数接收前端选中值,完成全局变量更新并反馈结果

内容的提问来源于stack exchange,提问作者Saud Malik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:07:26