我是 .gs 的新手,所以这应该不难。
我有一个 Google 电子表格,其中一列中有值(假设 A 列)。
我使用 .gs 创建了一个自定义菜单,用户将在其中选择一个选项。
单击其中一个选项(新组件),将出现一个弹出窗口,其中包含一个下拉菜单,用户应从其中选择值。
自定义菜单
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('bq Library Menu')
.addItem('Add new component', 'newComponent')
.addSeparator()
.addSubMenu(ui.createMenu('Modify existing component')
.addItem('Remove component', 'removeComponent'))
.addToUi();
}
function newComponent() {
var html = HtmlService.createHtmlOutputFromFile('NewComponentForm')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'New Component Form');
}
NewComponentForm.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h2>Clickable Dropdown</h2>
<p>Select manufacturer from the list</p>
<div class="dropdown">
<button onclick="loadManufacturers()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content"></div>
</div>
</body>
我希望下拉菜单显示电子表格中 A 列中的所有元素。我尝试了多种选择,但没有获得所需的结果。
那么,我需要如何继续实施下拉填充过程呢?
- 您想要创建一个选择框并输入电子表格“A”列中的值。
- 当选择选择框中的值时,您想要检索该值。
如果我的理解是正确的,那么这个修改怎么样?我认为针对您的情况有多种答案,因此请将此视为其中之一。
修改后的脚本的流程如下。
- 打开一个对话框。
- 单击“下拉”按钮。
- By
google.script.run
,运行函数getValuesFromSpreadsheet()
在 Google Apps 脚本端。
- At
getValuesFromSpreadsheet()
,从电子表格中检索值并将其返回到 Javascript。
- At
withSuccessHandler()
,检索返回值。使用这些值创建一个选择框。
- 当选择框的值被选中时,
selected()
运行并检索所选值。
当反映上述流程时,修改后的脚本如下。
GAS:
请将以下 Google Apps 脚本添加到CustomMenu.gs
.
function getValuesFromSpreadsheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
return sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues(); // Retrieve values and send to Javascript
}
- In this sample script, the values are retrieved from "Sheet1" of the active Spreadsheet. The values are in the column "A".
HTML:
请将以下 JavaScript 添加到NewComponentForm.html
.
<script>
function loadManufacturers() {
google.script.run.withSuccessHandler(function(ar) {
let select = document.createElement("select");
select.id = "select1";
select.setAttribute("onchange", "selected()");
document.getElementById("myDropdown").appendChild(select);
ar.forEach(function(e, i) {
let option = document.createElement("option");
option.value = i;
option.text = e;
document.getElementById("select1").appendChild(option);
});
}).getValuesFromSpreadsheet();
};
function selected() {
const value = document.getElementById("select1").value;
console.log(value);
}
</script>
- Use
google.script.run
用于从电子表格中检索值。
- Using
withSuccessHandler
,从 Google Apps 脚本检索值。
- 单击“下拉”按钮时,将创建一个选择框。
- 所选值可以在控制台中看到。
Note:
- 这是一个简单的示例脚本。所以请根据您的情况进行修改。
参考:
- 谷歌脚本运行 https://developers.google.com/apps-script/guides/html/reference/run
- 与成功处理程序 https://developers.google.com/apps-script/guides/html/reference/run#withSuccessHandler(Function)
如果我误解了你的问题,我很抱歉。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)