我有一个 google 表格,我在其中编写了一个自定义侧边栏。
在边栏中,我想在事件行中显示第 I 列的值。
我已经设法编写出在边栏打开时存储变量“I”的脚本:
var hotelName = ""
function openSidebar() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showSidebar(html);
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("Contract Registry Document");
var row=s.getActiveCell().getRow();
var column=9;
hotelName = s.getRange(row, column).getValue();
Logger.log(hotelName);
}
但是我现在需要它出现在我侧边栏的一个空 DIV 元素中。如何导出此变量?
更新:
效果很好。我现在还在边栏上添加了一个按钮来刷新,我想要做的是更新脚本,这样如果用户更改了行,就会显示新的酒店名称。目前我已经添加了这个 HTML:
<div id="footer">
<div><?= hotel ?></div>
<p><i class="fa fa-refresh" aria-hidden="true" id="testing"></i></p>
</div>
并将这个 JQuery 添加到索引文件中:
$("#testing").on('click', function buttonClick() {
google.script.run.buttonClick();
});
对于函数,我只是复制了原始函数:
function buttonClick() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("Contract Registry Document");
var row=s.getActiveCell().getRow();
var column=9;
var hotelName = s.getRange(row, column).getValue();
// get the html template after retrieving the values
var html_template = HtmlService.createTemplateFromFile('index');
// set the value for the index.html `hotel` placeholder/scriptlet
html_template.hotel = hotelName;
// evaluate the template
var sidebar_html = html_template.evaluate();
SpreadsheetApp.getUi().showSidebar(sidebar_html);
Logger.log(hotelName);
}
但是,我真的希望单元格的值异步更新,这样侧边栏就不会重新加载,只是酒店名称...
这可能吗??
最佳答案
在加载侧边栏时从电子表格中获取数据
在显示侧边栏之前不要忘记先选择行。
代码.gs
function openThisSideBar()
{
var html = HtmlService.createHtmlOutputFromFile('hotel').setTitle('MySideBar');
SpreadsheetApp.getUi().showSidebar(html);
}
function getHotel()
{
var s=SpreadsheetApp.getActive().getSheetByName("Contract Registry Document");
var row=s.getActiveCell().getRow();
var n=Utilities.formatString('Your Hotel is named: %s',s.getRange(row, 9).getValue());
return n;
}
function onOpen()
{
SpreadsheetApp.getUi().createMenu('MyTools')
.addItem('Open Sidebar', 'openThisSideBar')
.addToUi();
}
酒店.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function()
{
google.script.run
.withSuccessHandler(updateHotel)
.getHotel();
});
function updateHotel(name)
{
document.getElementById('hotel').innerHTML=name;
}
console.log('MyCode');
</script>
</head>
<body>
<div id="hotel"></div>
</body>
</html>
您可以像这样添加刷新:
<script>
function refresh()
{
google.script.run
.withSuccessHandler(updateHotel)
.getHotel();
}
</script>
以及新的 html:
<input type="button" value="Refresh" onClick="refresh();" />
That way you needn't refresh the entire page but just the div.
关于javascript - 在自定义 HTML 侧边栏中使用 .gs 文件中的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47306725/