在 javascript 中捕获事件
<!doctype html>
<html>
<body>
<div id = 'div' style = 'width:100px;height:100px;background:#000000;'></div>
<script type = 'text/javascript'>
document.getElementById('div').addEventListener('click',happen(),true);
function happen()
{
alert(1)
}
</script>
</body>
</html>
在上面的代码中,为什么当页面加载时会触发该事件,而当我单击 div 时不会触发该事件...另外,正确的事件名称是 click 或 onclick...
<!doctype html>
<html>
<body>
<div id = 'div' style = 'width:100px;height:100px;background:#000000;'></div>
<script type = 'text/javascript'>
document.getElementById('div').addEventListener('click',happen(),true);
function happen()
{
alert(1)
}
</script>
</body>
</html>
In the above code why the event is triggered when the page loads and not triggered when i click on the div...Also which is the correct event name click or onclick....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是因为您立即调用了该函数,并将其 null 结果传递给
addEventListener()
。它应该是:
如果你想将参数传递给
happen
,你必须这样写:It's because you've immediately called the function, and passed its null result to
addEventListener()
.It should be:
If you want to pass arguments to
happen
, you'd have to write this:您立即调用该函数并将其返回值传递给
addEventListener
,就像任何其他函数调用一样。取出
()
。You're calling the function immediately and passing its return value to
addEventListener
, just like any other function call.Take out the
()
.这应该有效:
This should work:
问题出在这一行:
您应该只传递函数
happen
的名称,但由于添加了括号,所以您正在传递结果。试试这个:
The problem is with this line:
You should should only be passing the name of the function
happen
but since you added the parentheses, you are passing the result.Try this instead:
正如其他回答者所说,去掉()将解决问题。
另一种方法是将函数包装在
function(){ }
中,这对于 OO Javascript 来说是一个很好的实践,如下所示:document.getElementById('div').addEventListener('click ',function(){happen()},true);
如果回调需要在对象内执行(在本例中不需要),这将保留范围。
As the other answerers have said, taking out the () will fix the problem.
An alternative, and a good practice for OO Javascript, is to wrap the function inside a
function(){ }
, like so:document.getElementById('div').addEventListener('click',function(){happen()},true);
That will retain scope if the callback needs to execute within an object (in this case it does not).
事件处理程序不需要括号
The event handler does not need parenthesis