简体   繁体   English

Onclick在没有点击的情况下被解雇

[英]Onclick gets fired without clicking

en.onclick = setCookie('english');

Why does this get fired without even clicking on it? 为什么没有点击它就会被解雇?

I have 3 flags that should set a cookie to their language when clicked wit the last one always gets fired right away... 我有3个标志,当点击时应该设置一个cookie到他们的语言,最后一个总是被立即解雇...

Your code above evaluates setCookie('english') and puts its returned value (if any) into en.onclick . 上面的代码评估setCookie('english')并将其返回值(如果有)放入en.onclick In order to assign it as an event handler, wrap it into a function: 要将其指定为事件处理程序,请将其包装到函数中:

en.onclick = function(){
   setCookie('english');
};

cause you must use something like that 因为你必须使用类似的东西

en.onclick=function(){
  setCookie('english');
}

Because you're invoking the method setCookie(...) . 因为你正在调用方法setCookie(...) Try this: 尝试这个:

en.onclick = setCookie;

With the brackets you're invoking the method; 使用括号,您将调用该方法; without you're handing it as an object. 没有你把它作为一个对象。

Or try this: 或试试这个:

en.onclick = function() { setCookie('english') };

Here we create a new function which calls setCookie with the appropriate argument. 这里我们创建一个新函数,它使用适当的参数调用setCookie

Well that's because you're running the method and assigning the result to en.onclick. 那是因为你正在运行方法并将结果分配给en.onclick。

What you probably want to do us 你可能想要做什么

en.onclick = function(){setCookie('english');};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM