我正在嘗試將選項加載到 Google 表格中的選擇框中。我的代碼目前幾乎可以作業,但是,當頁面首次顯示時,初始選擇選項沒有將相應的值加載到文本輸入框中。更改選擇框選項時,該值會正確加載到文本框中。如何在初始頁面加載時同時加載選項和值?
代碼.gs
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu("Sidebar")
.addItem("Show sidebar", "showSidebar")
.addToUi();
}
function showSidebar() {
var htmlWidget = HtmlService.createHtmlOutputFromFile('Test')
SpreadsheetApp.getUi().showSidebar(htmlWidget);
}
function getList() {
var items = SpreadsheetApp.getActive().getRange("Sheet1!A1:B3").getValues();
return items;
}
測驗.html
<!DOCTYPE html>
<html>
<script>
function loadSelectBox() {
google.script.run.withSuccessHandler(function(ar)
{
var itemList = document.getElementById("itemSelectBox");
ar.forEach(function(item, index)
{
var option = document.createElement("option");
option.value = item[1];
option.text = item[0];
itemList.appendChild(option);
});
}).getList();
getPath();
}
function getPath()
{
var path = document.getElementById("itemSelectBox").value;
document.getElementById("itemPath").value = path;
}
</script>
<head>
<base target="_top">
</head>
<body>
<select id="itemSelectBox" onchange="getPath()" style="width: 60%"></select>
<br>
<input type="text" id="itemPath" style="width: 60%">
<script>
loadSelectBox();
</script>
</body>
</html>
uj5u.com熱心網友回復:
在您的腳本中,如何進行以下修改?
修改后的腳本:
請loadSelectBox()進行如下修改。
function loadSelectBox() {
google.script.run.withSuccessHandler(function (ar) {
var itemList = document.getElementById("itemSelectBox");
ar.forEach(function (item, index) {
var option = document.createElement("option");
option.value = item[1];
option.text = item[0];
itemList.appendChild(option);
});
getPath(); // <--- Modified
}).getList();
}
- 在您的放映腳本中,
getPath();放在google.script.run.google.script.run與異步行程一起運行。這樣,beforewithSuccessHandleris run,getPath()is run。我認為這是您問題的原因。
參考:
- 類 google.script.run(客戶端 API)
uj5u.com熱心網友回復:
我認為問題在于您在標頭中有 javascript,因此它在創建 dom (html) 之前運行。
您可以
a) 將您的 javascript 移動到最后
b) 一旦https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event被觸發就觸發您的代碼。
替代 a 可能會更好,但除非你真的必須這樣做,否則混合 html 和 JS 并不好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/524241.html
上一篇:表格API匯入表格與格式化
