javascript - 按钮onclick,执行JS函数再执行JS代码

标签 javascript google-apps-script onclick

抱歉英语错误,但我不是英语。

从这个例子开始Form to upload files with sending email address很久以前我已经将按钮代码更改为:

  <input type="button" value="Submit"
      onclick="google.script.run
          .withSuccessHandler(updateUrl)
          .withFailureHandler(onFailure)
          .uploadFiles(this.parentNode)" />

至:

<input type="button" value="Submit"
      onclick="test()" />

完整的 HTML 页面是:

<form id="myForm">
  <input type="text" name="myName" placeholder="Your full name..."/>
  <input name="myFile" type="file" />
  <input type="button" value="Submit"
      onclick="test()" />
</form>

<div id="output"></div>

<script>
    function test(){
    console.log ("I'm running");
    
    google.script.run
          .withSuccessHandler(updateUrl)
          .withFailureHandler(onFailure)
          .uploadFiles(this.parentNode)
          
    }

    function updateUrl(url) {
        var div = document.getElementById('output');
        div.innerHTML = '<a href="' + url + '">Got it!</a>';
    }
    function onFailure(error) {
        alert(error.message);
    }
</script>

<style>
  input { display:block; margin: 20px; }
</style>

它工作了一年,几天前就停止了。 如果我打开控制台,我会正确看到“我正在运行消息”,但电子表格或文件夹中没有任何反应。

有人能告诉我为什么吗? 我需要在执行 GS 代码之前运行一些 JS 代码,它可以工作,但现在不行,改变了什么?

谢谢。

最佳答案

当您移动google.script.run.myFunction()时代码从按钮到 <script>标签,它会导致 this关键字来指代不同的东西。所以,this.parentNode不再引用带有 google.script.run.myFunction() 的表单元素代码在 <script>标签。您需要使用

获取表单元素
var theForm = document.getElementById("myForm");

然后使用:

google.script.run.myFunction(theForm).

或者:

而不是使用 var theForm = document.getElementById("myForm");

您可以通过以下方式传递表单元素:

<input type="button" value="Submit" onclick="test(this.parentNode)" />

还有:

function test(theForm){

关于javascript - 按钮onclick,执行JS函数再执行JS代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37138022/

相关文章:

javascript - 如何根据数组中的值删除对象?

javascript - 使用jquery将json导入到html输入字段

google-apps-script - 如何在饼图中显示值 - Google Apps 脚本

JavaScript + Drupal

html - 在 appengine 中使用 "onclick"和单选按钮

javascript - 使用正则表达式替换字符串的一部分

javascript - [papaparse]解析错误处理程序

arrays - setValues 不能将数组转换为对象[][]

javascript - if 语句在条件满足后不停止

javascript - 调用其他标签的onclick事件