onmouseover和onmouseout事件在页面加载时触发,而不是在事件上触发

时间:2013-06-07 20:59:17

标签: javascript javascript-events

我有以下代码

var statusList = document.createElement('ul'); //I am populating this list elsewhere
statusList.style.display = 'none';
var statusSpan = document.createElement('span');
statusSpan.onmouseover = mapControlHover(statusList);
statusSpan.onmouseout = mapControlNoHover(statusList);

function mapControlHover(element) {
  element.style.display = 'block';
}

function mapControlNoHover(element) {
  element.style.display = 'none';
}

两个事件都是在页面加载时触发(他们不应该这样做)。无论是在onmouseover还是onmouseout被解雇。

请不要回答jquery。感谢

1 个答案:

答案 0 :(得分:1)

是的,因为你正在调用事件

statusSpan.onmouseover = mapControlHover(statusList);

你应该只传入事件处理函数引用。

statusSpan.onmouseover = mapControlHover

function mapControlHover() {
  statusList.style.display = 'block'; //access statusList directly here.
}

您还可以使用function.bind,查看IE的支持和polyfill< 9

 statusSpan.onmouseover = mapControlHover.bind(statusSpan, statusList);

并访问

function mapControlHover(element) {
  element.style.display = 'block'; 
}