我有以下代码

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';
}


这两个事件都在页面加载时触发(它们不应该触发)。在mouseoverover或onmouseout上都不会被解雇。

请没有jQuery的答案。谢谢

最佳答案

是的,这是因为您正在调用事件

statusSpan.onmouseover = mapControlHover(statusList);


您应该只传递事件处理程序函数参考。

statusSpan.onmouseover = mapControlHover




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


您也可以使用function.bind,请参见以获得支持和IE
 statusSpan.onmouseover = mapControlHover.bind(statusSpan, statusList);


和访问

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

09-18 19:11