onclick 函数自动运行 [英] onclick function runs automatically

查看:41
本文介绍了onclick 函数自动运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用谷歌应用程序脚本时,我在运行传递参数的 js 函数时遇到问题.当我添加参数时,它将始终在页面加载时运行代码,而不是在单击按钮时运行.

Using google apps script I'm having trouble running a js function which passes parameters. When I add the parameters it will always run the code when the page loads instead of when the button is clicked.

直接来自 HtmlService 示例,没问题-按下按钮时运行...

Direct from the HtmlService example, it is OK - it runs when the button is pressed...

document.getElementById('button1').onclick = doSomething;

但是当我向调用(和函数)添加一个参数时,如下所示,它只在页面加载时运行一次(而不是在按下按钮时)...

But when I add a parameter to the call (and function) as below, it runs just once when the page loads (and not when the button is pressed)...

document.getElementById('button1').onclick = doSomething('with_this_parameter');

对这种行为的任何见解将不胜感激......如果答案很明显,抱歉!

Any insight into this behaviour would be greatly appreciated... sorry if the answer is obvious!

推荐答案

当你说

document.getElementById('button1').onclick = doSomething('with_this_parameter');

这意味着调用doSomething('with_this_parameter'),然后将返回值分配给document.getElementById('button1').onclick.因此,这就是当代码到达该行时它被调用的原因.该值是否可分配给该属性是另一个问题,但这就是它被调用的原因.

This means call doSomething('with_this_parameter') and then assign the returned value to document.getElementById('button1').onclick. Hence that is why it gets called when code reaches that line. Whether the value is assignable to that property or not is another question, but that is why it gets called.

像这样使用

document.getElementById('button1').onclick = function(){
    doSomething('with_this_parameter');
}

参考:此解决方案由 Mark Linus 提供.

Reference: This solution was given by Mark Linus.

这篇关于onclick 函数自动运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆