Button onClick的变量未从Code.gs传递到JavaScript.html



我有一个简单的WebApp。

我在另一个文件中写了脚本(不是直接在Index.html中(

我成功地将onClick属性从Index.html设置为ButtonA

并尝试从JavaScript.html文件中将另一个onClick属性设置为ButtonB。但它不起作用:(

出了什么问题,或者如何做到这一点。。?

WebApp链接

应用程序脚本链接

下面是Code.gs文件

function doGet() {
var template = HtmlService.createTemplateFromFile('Index.html') ;
var TodaysUrl = "https://google.com" ;
template.TodaysUrl = TodaysUrl;
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent() ;
}

下面是Index.html文件

<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
.button {
display : block ;
text-align : center ;
margin : 25px auto ;
padding : 10px
}
</style>
</head>
<body>

<button class="button" id="btn-a" >ButtonA Link from Index.html</button>
<button class="button" id="btn-b" >ButtonB Link from JavaScript.html</button>
<script>
document.getElementById("btn-a").onclick = function () { window.open("<?= TodaysUrl ?>" )} ;
</script>  
<?!= include('JavaScript'); ?>
</body>
</html>

下面是JavaScript.html文件

<script>
document.getElementById("btn-b").onclick = function () { window.open("<?= TodaysUrl ?>" )} ;
</script>  

提前感谢

您的第二个按钮不工作,因为它是在第二次加载的,并且不是由"评估";作用

doGet>评估(定义btnA(>包括JS文件(其中包含btnB,因此不会渲染(

我的建议是在加载DOM后使用一个自定义函数来初始化按钮。这里有一个例子,有2个不同的URL

代码.gs

function doGet() {
var template = HtmlService.createTemplateFromFile('Index.html') ;
// var TodaysUrl = "https://google.com" ;
// template.TodaysUrl = TodaysUrl;
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent() ;
}
function initialize() {
var obj = {};
obj.url_a = "http://google.com";
obj.url_b = "http://amazon.com";
return obj;
}

Index.html

<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
.button {
display : block ;
text-align : center ;
margin : 25px auto ;
padding : 10px
}
</style>
</head>
<body>

<button class="button" id="btn-a" >ButtonA</button>
<button class="button" id="btn-b" >ButtonB</button>
<?!= include('JavaScript'); ?>
</body>
</html>

Javascript.html

<script>
document.addEventListener("DOMContentLoaded", function() {
google.script.run.withSuccessHandler(return_initialize).initialize();
});
function return_initialize(obj) {
document.getElementById("btn-a").onclick = function () { window.open(obj.url_a)} ;
document.getElementById("btn-b").onclick = function () { window.open(obj.url_b)} ;
}
</script>  

您需要将TodaysUrl传递给模板。

function doGet() {
var TodaysUrl = "https://google.com" ;
var template = HtmlService.createTemplateFromFile('Index') ;
template.TodaysUrl = TodaysUrl;
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

将脚本包含在html的正文中,而不是其他文件中。

最新更新