onclick函数自动运行

T-L*_*T-L 15 javascript web-applications google-apps-script dom-events

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

直接从HtmlService示例,它是正常的 - 它按下按钮时运行...

document.getElementById('button1').onclick = doSomething;
Run Code Online (Sandbox Code Playgroud)

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

document.getElementById('button1').onclick = doSomething('with_this_parameter');
Run Code Online (Sandbox Code Playgroud)

如果答案显而易见,那么对此行为的任何见解都将非常感激...对不起!

Han*_*nky 33

当你说

document.getElementById('button1').onclick = doSomething('with_this_parameter');
Run Code Online (Sandbox Code Playgroud)

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

像这样使用它

document.getElementById('button1').onclick = function(){
    doSomething('with_this_parameter');
}
Run Code Online (Sandbox Code Playgroud)

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


Dan*_*nte 10

这样做:

document.getElementById('button1').onclick = function(){
    doSomething('with_this_parameter');
}
Run Code Online (Sandbox Code Playgroud)