简体   繁体   English

为什么不能直接分配功能?

[英]Why can't I assign a function directly?

This code calls the f() function: 此代码调用f()函数:

<p id="firstp">Hello!</p> 
<script>
  function f() {
    doSomething();
  };
  document.getElementById("firstp").onmouseover = function() {
      f();
  };
</script>

Yet if I write it this way, it stops working: 但是,如果我这样写,它将停止工作:

  document.getElementById("firstp").onmouseover = f();

Why doesn't the event handler get set when I call the function directly? 当我直接调用函数时,为什么没有设置事件处理程序?

Because you don't want to call the function, you want just to tell the browser that it should call it when mouseover event happens. 因为您不想调用该函数,所以只想告诉浏览器在发生mouseover事件时应调用该函数。 f() (round brackets after function's name) calls the function and assigns to .onmouseover what f returns. f() (函数名称后的圆括号)调用函数并将f返回的值分配给.onmouseover You want to assign the reference to f to .onmouseover , so what you are looking for is 您想要将对f的引用分配给.onmouseover ,所以您正在寻找的是

document.getElementById("firstp").onmouseover = f;

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

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