【问题标题】:button will not execute click function in google apps script html service按钮不会在谷歌应用脚​​本 html 服务中执行点击功能
【发布时间】:2019-06-02 03:58:22
【问题描述】:

我已经花了 2 天的时间试图解决这个问题,因此感谢您的帮助。

我在关注这个nice little video tutorial series 我想在进一步了解之前尝试一些基本的东西:使用 google 应用程序脚本及其 HTML 服务组件获取一个 html 按钮以显示 javascript 警报,但对于我来说,我无法理解为什么没有触发警报。

这是我的代码

索引.html

    <!DOCTYPE html>
        <html>
          <head>
              <script>
                 document.getElementById("btnSearch")
                         .addEventListener("click",showAlert);                
              function showAlert() {
                alert("hello world");
              }
              </script>
          </head>
          <body>
            <div>
              <label>Enter code</label>
              <input type="text" id="txtStudentID"/>
              <button id="btnSearch">Search</button>
            </div>
          </body>
        </html>

和我的 代码.gs

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

我也尝试过,就像谷歌显示它here:但我仍然没有在按下按钮后触发警报:

<input type="button" value="Search"
      onclick="google.script.run
          .withSuccessHandler(showAlert)
          .withUserObject(this)" />

就像在脚本标签中以“document.getElementByID...”开头的任何东西都不起作用

我错过了什么?这是 GAPS 不再支持的东西吗?有没有其他/正确的方法可以让它工作?

提前谢谢你。

【问题讨论】:

    标签: javascript google-apps-script web-applications


    【解决方案1】:

    脚本标签中以“document.getElementByID...”开头的任何内容都无法正常工作

    是的。因为在评估脚本标签时,没有 ID 为 btnSearch 的元素。

    解决方案:

    • 将脚本移动到 DOM 的底部。
    <div>
      <label>Enter code</label>
      <input type="text" id="txtStudentID" />
      <button id="btnSearch">Search</button>
    </div>
    
    <script>
      function showAlert() {
        alert('hello world');
      }
      document.getElementById('btnSearch').addEventListener('click', showAlert);
    </script>
    
    • 或者,如前面的答案所述,使用load 触发器;以便在加载 DOM 后评估​​脚本。
    <script>
      function showAlert() {
        alert('hello world');
      }
      function load1() {
        document.getElementById('btnSearch').addEventListener('click', showAlert);
      }
      window.addEventListener('load', load1);
    </script>
    

    【讨论】:

    • 非常感谢你。我知道我错过了一些小东西。
    【解决方案2】:

    尝试将 addEvent 放入 window.onload

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      相关资源
      最近更新 更多