javascript - 使用谷歌应用脚​​本创建按钮和输入字段

标签 javascript google-apps-script

我想在用户按下 Google App Scripts 中的按钮时提醒用户。以下代码为 JS 和 HTML:

<html>    
    <body>
        <button onclick='myFunction()'> Press this </button>
    </body>
</html>
<script>
function myFunction()
{
   var b = document.getElementById('result');    
   b.innerHTML = 'You pressed the button.';    
   alert('The output has been modified');    
   return;    
}    
</script>

我将它输入到一个 HTML 文件中,但我无法理解如何运行它。它给了我一个只运行该功能的选项。当我这样做时,出现以下错误:

ReferenceError: “文档”未定义

我尝试将其部署为 Web 应用程序,但即使这样也行不通。按钮出现,但单击它时没有任何反应。

告诉我如何解决这个问题。

最佳答案

您将通过阅读 Html Service - Google Apps Script 找到大部分答案。 .运行它的方式是创建一个已发布的 script-as-web-app .

Html 服务是一种选择,但您也可以使用 UiApp 服务 - 查看 Call a Google Apps Script function in HTML有关使用该方法的示例。


myFunction()中使用以下代码,您正在修改名为 innerHTML 的元素的内容 ( result) .这就是您动态更改显示页面的方式。

var b = document.getElementById('result');
b.innerHTML = 'You pressed the button.';

问题是,您没有这样的元素。让我们添加一个 <div> .只是为了制作myFunction()的效果很明显,我们将从一些内容开始,但这是可选的。重要的是我们为元素提供了一个 id,在本例中为“result”,以匹配函数中已有的 id。

<div id="result">You haven't pressed the button yet.</div>

这是最终代码。除了“结果”变化之外,<script> block 在 <html> 内移动标签,并在您的按钮中添加了一个 id,允许在单击后将其禁用。如屏幕截图所示,您将在编辑器中有两个文件。

Screenshot - Editor with two files

代码.gs

没什么大不了的,它与Creating HTML Files中描述的完全一样

function doGet() {
  return HtmlService.createHtmlOutputFromFile('myPage');
}

我的页面.html

同样,从 Html Service 中的示例开始.注意 .createHtmlOutputFromFile('myPage')doGet()包含脚本中 html 文件的名称。 (如果我每次因为剪切和粘贴而搞砸它时得到一美元,我就会得到两美元。)

<html>
  <script>
    function myFunction() {
      var b = document.getElementById('result');
      b.innerHTML = 'You pressed the button.';
      document.getElementById('button1').disabled = 'disabled';
      //alert('The output has been modified');
      return;
    }
  </script>

  <body>
    <button onclick='myFunction()' id='button1'>Press this</button>
    <div id="result">You haven't pressed the button yet.</div>
  </body>
</html>

关于javascript - 使用谷歌应用脚​​本创建按钮和输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495268/

相关文章:

javascript - Google 表格 - 表单提交时的格式日期

javascript - 手动添加片段到react-ace编辑器

javascript - PHP/AJAX 从ajax获取id

javascript - JavaScript 中索引和数据的区别?

authentication - 如何使用带有凭据的 UrlFetchApp?谷歌脚本

javascript - 通过 Google App Script 调用 AWS Lambda 函数

javascript - 根据 SOLID 编写 JavaScript

javascript - Ionic 应用程序和服务器帖子 : Acces-Control-Allow-Origin

google-apps-script - 我可以自动将标题文本添加到 Google 文档文件的页脚吗?

javascript - 如何从 Google Sheet App Script 返回#N/A?