简体   繁体   English

Google Apps脚本使用功能写入HTML

[英]Google Apps Script write to HTML with Function

I am trying to write a Google Apps Script that when published as a Web App will have a button, which when pressed, will call a function from Code.gs that will reveal or hide a piece of html (in effect, change the style of the div with a specific ID). 我正在尝试编写一个Google Apps脚本,当它作为Web应用发布时,将具有一个按钮,当按下该按钮时,它将调用Code.gs中的一个函数,该函数将显示或隐藏一段html(实际上,更改html的样式具有特定ID的div)。

This is a small case example I've set up: 这是我设置的一个小案例:

My index.html file: 我的index.html文件:

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>

<body>

  <button onclick="google.script.run.myFunction()">Click Me</button>

  <div id="myDIV">
    This is my DIV I want to Reveal/Hide.
  </div>

 </body>
</html>

My Code.gs file: 我的Code.gs文件:

function doGet() {
  var template = HtmlService.createTemplateFromFile("index.html");
  var html = template.evaluate();
  return HtmlService.createHtmlOutput(html);
  }

function myFunction() {  
  var x = document.getElementById("myDIV");/*Where the Reference Error Shows Up*/
  if (x.style.display === "none") {
    x.style.display = "block";
    } 
    else {
      x.style.display = "none";
      }
   }

The error I keep getting when debugging is: ReferenceError: "document" is not defined. 我在调试时不断遇到的错误是:ReferenceError:未定义“文档”。 When published, the button appears with myDIV visible, and clicking the button does nothing. 发布后,该按钮将显示myDIV,并且单击该按钮将不执行任何操作。

I am assuming the problem is that I should not be using document.getElementByID(), but rather somethingelse.getElementByID(), but I don't know what that something else is. 我假设问题是我不应该使用document.getElementByID(),而应该使用somethingelse.getElementByID(),但是我不知道那是什么。 Most cases that I look for online are not specific to Google Web Apps. 我在网上寻找的大多数情况并非特定于Google Web Apps。 Any help would be appreciated. 任何帮助,将不胜感激。

You need to take care about where each code is executed : the GS code is executed on "server side" and so can't refer to document which is a navigator ("client side") variable. 您需要注意每个代码的执行位置:GS代码是在“服务器端”执行的,因此不能引用作为导航器(“客户端”)变量的document

Add myFunction() to your HTML and call it directly with onclick="myFunction();" myFunction()添加到您的HTML中,然后直接使用onclick="myFunction();"调用onclick="myFunction();" , that should do the trick. , 这应该够了吧。

Regards, 问候,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM