为什么在Javascript事件处理函数中使用括号? [英] Why in Javascript event handler functions with parentheses?

查看:131
本文介绍了为什么在Javascript事件处理函数中使用括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript专家,看看这段代码:

Javascript gurus, look at this code:

<button onclick="handler()">ClickMe</button>
        <script>
            function handler() {
            alert("clicked");
        }
     </script>

为什么onclick事件应该用()onclick =handler()分配给处理程序?
在这种情况下,会调用警报。但根据所描述的逻辑,作为对类似问题的回答 https://stackoverflow.com/a/3247044/2543590 onclick已分配到函数处理程序的结果,而不是自己运行。
我相信指定onclick功能它应该是这样的

Why onclick event should be assigned to handler with () onclick="handler()"? In this case alert is called. But according to the logic described as answer to similar question https://stackoverflow.com/a/3247044/2543590 onclick assigned to result of function handler, not to function itself. I believe to assign onclick to function it should be like this

onclick="handler", 

但在这种情况下不会调用警报。
为什么?

but in this case alert is not called. Why?

推荐答案

内联JS



当您执行内联onclick处理程序时那个,你要分配一个Javascript表达式来运行。所以你需要执行这个函数。

Inline JS

When you do an inline onclick handler like that, you're assigning a Javascript expression to run. So you need to execute the function.

表达式可以很容易地 onclick =handler(); alert(2)在这种情况下显然需要调用该函数,就像从javascript文件运行一样。

The expression could just as easily be onclick="handler();alert(2)" in which case its obvious that the function needs to be called, just like it would be if it were run from a javascript file.

如果你用javascript附加click事件,你将绑定一个函数,所以你只需要传递函数对象。

If instead you attach the click event with javascript, you would be binding a function, so you just need to pass the function object.

var btn = document.getElementById("btn");
btn.addEventListener("click",handler);

addEventListener 设置要绑定的函数对象到事件,以便在事件被触发时执行。由于您指定的是函数对象而不是字符串表达式,因此不需要括号。事实上,如果你添加它们,函数将立即执行,函数的返回值将绑定到事件。

addEventListener sets the function object to be bound to the event so that it executes when the event is triggered. Since you're specifying a function object, rather than a string expression, the parentheses are not needed. In fact if you added them the function would execute immediatelly and the return value of the function would be bound to the event.

一般来说,大多数人会主张通过绑定函数处理程序而不是使用内联JS来绑定javascript中的事件。它更容易调试,不会将您的逻辑紧密绑定到DOM,并且对动态页面更灵活。它还会强制你进行任何你称之为全局的函数。

In general most people would advocate you bind events in javascript by binding a function handler rather than using inline JS. Its easier to debug, doesn't tightly bind your logic to the DOM, and is more flexible for dynamic pages. It also forces you to make any functions that you're calling global.

关键是属性指向一个被评估为JS表达式的字符串,它与将一个函数对象绑定到该事件不同。

The key is the attribute points to a string that is evaluated as a JS expression, it is not the same as binding a function object to the event.

这篇关于为什么在Javascript事件处理函数中使用括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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