事件未定义(javascript

时间:2018-03-26 21:10:01

标签: javascript function

我想添加一个事件管理器但是,它不起作用?

控制台显示我

"ReferenceError: event is not defined"

document.getElementsByTagName('div')[0].addEventListener("mousemove", myFunction(event));

function myFunction(event) {
    var x = event.pageX;
    var y = event.pageY;
    var coor = "Coordinates: (" + x + "," + y + ")";
    document.getElementByTagName('p')[0].textContent = coor;
}
<div> 
<p></p>
</div>

2 个答案:

答案 0 :(得分:0)

创建事件侦听器时,请编写该函数的唯一名称:

element.addEventListener("mousemove", myFunction);

document.getElementsByTagName('div')[0].addEventListener("mousemove", myFunction);

function myFunction(event) {
    var x = event.pageX;
    var y = event.pageY;
    var coor = "Coordinates: (" + x + "," + y + ")";
    document.getElementsByTagName('p')[0].textContent = coor;
}
div {
  background-color: red;
  width: 200px;
  height: 200px;
}
<div>
  <p></p>
</div>

答案 1 :(得分:0)

虽然Vadim Shashkov是正确的,但背后有更多的理由。根据Mozilla(https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)提供的文档,您为addEventListener函数赋予了值而不是函数。你需要赋予它功能,这就是为什么

document.getElementById('myDiv').addEventListener("mousemove", myFunction);

作品。