返回
如何使用 Google Apps 脚本创建带有加减按钮的 Web 应用程序计数器?
javascript
2024-03-16 20:30:44
使用 Google Apps 脚本构建带有加减按钮的 Web 应用程序计数器
背景
计数器是一个简单的应用程序,用于跟踪数字并根据需要增加或减少它。使用 Google Apps 脚本,你可以轻松地创建带有增加和减少按钮的 Web 应用程序计数器,并在按钮单击时更新计数。这篇教程将指导你完成创建此应用程序所需的步骤。
HTML 页面
首先,创建一个 HTML 文件(index.html)并输入以下代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div class="container">
<h2><span id="count">0</span></h2>
<button id="decBtn" class="button" onclick="onDec()">-</button>
<button id="incBtn" class="button" onclick="onInc()">+</button>
</div>
<script type="text/javascript" src="code.js"></script>
</body>
</html>
该代码定义了一个简单的 Web 页面,其中包含一个显示计数的标题 (h2) 和两个用于增加和减少计数的按钮。
Google Apps 脚本代码
在 Google Apps 脚本编辑器中,创建一个新脚本文件(code.gs)并输入以下代码:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
let count = 0;
const counter = document.getElementById('count');
function onDec() {
count = count - 1;
counter.textContent = count;
}
function onInc() {
count = count + 1;
counter.textContent = count;
}
该代码包含以下功能:
- doGet() 函数将 index.html 文件的内容作为 Web 应用程序返回。
- count 变量存储计数的值。
- onDec() 函数在单击减号按钮时减少计数。
- onInc() 函数在单击加号按钮时增加计数。
部署 Web 应用程序
- 在脚本编辑器中,单击“发布”>“部署为 Web 应用程序”。
- 选择“作为我自己的 Web 应用程序部署”。
- 单击“部署”。
- 复制并粘贴 URL 以访问你的 Web 应用程序。
测试 Web 应用程序
- 打开 Web 应用程序 URL。
- 单击加号按钮 (+) 增加计数。
- 单击减号按钮 (-) 减少计数。
结论
通过遵循这些步骤,你已经成功创建了一个带有加减按钮的简单 Web 应用程序计数器。这个应用程序是理解 Web 应用程序开发基础的一个很好的起点,还可以进一步扩展以包含其他功能,例如持久性存储或与其他 Google 服务的集成。
常见问题解答
- 如何更改按钮的样式?
你可以通过在 index.html 文件中添加 CSS 来更改按钮的样式。
- 如何将计数存储在 Google 表格中?
你可以使用 Google Apps 脚本将计数存储在 Google 表格中。
- 如何从其他 Web 应用程序访问计数器?
你可以使用 Google Apps 脚本的 Content Service 从其他 Web 应用程序访问计数器。
- 如何让计数器自动更新?
你可以使用 Google Apps 脚本的触发器让计数器自动更新。
- 如何部署计数器到自己的域?
你可以通过使用 Cloud Functions for Firebase 将计数器部署到自己的域。