Google Sheets脚本问题:多选弹窗答案写入位置错误求助
问题定位与修复方案
错误原因
你在Google Apps Script中定义了两个同名的writeChoice函数,在JavaScript运行环境里,后续定义的同名函数会完全覆盖之前的。所以无论你调用多少次writeChoice,实际执行的都是第二个负责写入B1单元格的函数,这就导致问题1的答案被错误写入到问题2的目标单元格中。
修复步骤
1. 修改Google Apps Script代码
将两个重复的writeChoice函数合并为一个,一次性处理两个选项的写入操作,减少服务端调用次数:
function start() { var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.getRange('A1:B1').clear({contentsOnly: true, skipFilteredRows: true}); spreadsheet.getRange('A10').activate(); // START HTML POP-UP dropDownModal() }; function dropDownModal() { var htmlDlg = HtmlService.createHtmlOutputFromFile('dropdown.html') .setSandboxMode(HtmlService.SandboxMode.IFRAME) .setWidth(350) .setHeight(175); SpreadsheetApp.getUi() .showModalDialog(htmlDlg, 'Box title'); }; // 合并为单个函数,接收两个选择参数 function writeChoices(selection1, selection2) { const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; sheet.getRange("A1").setValue(selection1); sheet.getRange("B1").setValue(selection2); }
2. 修改dropdown.html代码
更新提交函数,调用合并后的writeChoices函数,同时给按钮添加type="button"避免表单默认提交行为:
<!DOCTYPE html> <html> <head> <base target="_top"> </head> <script> function onSuccess1() { google.script.host.close(); } function submit1() { const choice1 = document.getElementById('choice1').value; const choice2 = document.getElementById('choice2').value; google.script.run .withSuccessHandler(onSuccess1) .writeChoices(choice1, choice2); // 调用合并后的函数 } function setup1() { const button = document.getElementById('submitbutton1'); button.addEventListener("click", submit1) } </script> <body onload="setup1()"> <p> Text 1. </p> <form> <select id="choice1"> <option value="choice 1-A">choice 1-A</option> <option value="choice 1-B">choice 1-B</option> <option value="choice 1-C">choice 1-C</option> </select> <br><br> <select id="choice2"> <option value="choice 2-A">choice 2-A</option> <option value="choice 2-B">choice 2-B</option> <option value="choice 2-C">choice 2-C</option> </select> <br><br> <!-- 添加type="button"防止表单默认提交 --> <button id="submitbutton1" type="button">Hit it 1</button> </form> </body> </html>
备选方案(保留两个独立函数)
如果你坚持使用两个独立函数,需要给它们不同的命名,同时注意google.script.run的异步特性:
修改后的GS函数:
function writeChoice1(selection1) { SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange("A1").setValue(selection1); } function writeChoice2(selection2) { SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange("B1").setValue(selection2); }
修改后的HTML提交函数:
function submit1() { const choice1 = document.getElementById('choice1').value; const choice2 = document.getElementById('choice2').value; // 先调用第一个写入函数,成功后再调用第二个 google.script.run .withSuccessHandler(() => { google.script.run.withSuccessHandler(onSuccess1).writeChoice2(choice2); }) .writeChoice1(choice1); }
内容的提问来源于stack exchange,提问作者Tim Harris
相关产品推荐
相关产品推荐

