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

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

问题描述

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



直接从HtmlService例子中,它运行正常 - 它运行当按下按钮时...

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

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

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

对此行为的深入了解将不胜感激......对不起,如果答案显而易见!

解决方案

当你说

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

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



像这样使用它

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

参考:此解决方案由 Mark Linus

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.

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!

解决方案

When you say

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

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.

Use it like this

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

Reference: This solution was given by Mark Linus.

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

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