Javascript 鼠标悬停不起作用
我有一个div正在等待移动事件。然后放置一个包含相关信息的div 我遇到的问题是如何正确地删除事件侦听器&同时删除它创建的div。。。由于某种原因,它找不到我制作的子div 这是我试过的脚本:Javascript 鼠标悬停不起作用,javascript,Javascript,我有一个div正在等待移动事件。然后放置一个包含相关信息的div 我遇到的问题是如何正确地删除事件侦听器&同时删除它创建的div。。。由于某种原因,它找不到我制作的子div 这是我试过的脚本: div.addEventListener('mouseover',bubble_info,false); function bubble_info(e){ var x = e.pageX + 50; //push it 50px to the right var div = docum
div.addEventListener('mouseover',bubble_info,false);
function bubble_info(e){
var x = e.pageX + 50; //push it 50px to the right
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = e.pageY;
div.style.left = x;
div.className = 'bubble';
div.innerHTML = 'Testing this div';
this.appendChild(div);
//stop firing if mouse moves around on the parent as it is still "over" the parent
this.removeEventListener('mouseover',bubble_info,false);
//when mouse out occurs the below should fire
this.addEventListener('mouseout',function(){clear_hover.call(this,div);},false);
}
function clear_hover(child){
//remove the bubble div we made
child.parentNode.removeChild(child);
//remove the mouse out as we are now out
this.removeEventListener('mouseout',function(){clear_hover.call(this,div);},false);
//re-add the mouseover listener encase user hovers over it again
this.addEventListener('mouseover',bubble_info,false);
}
任何人都能看到我在这里犯的错误,只是不明白为什么鼠标出了问题
开发工具显示
无法调用null的方法'removeChild
错误提示child.parentNode==null
。因此,元素没有要从中删除的parentNode
if (child.parentNode)
child.parentNode.removeChild(child);
但是,这只能解决问题。实际问题是没有删除事件处理程序,因此它会在后续出现的mouseout
事件中继续运行
虽然以下功能相似,但它们必须相同才能成功删除
this.addEventListener('mouseout',function(){clear_hover.call(this,div);},false);
因此,您需要保存对函数的引用以将其删除:
function bubble_info(e){
var ...;
function on_mouseout() {
// pass a reference to the `function` itself
clear_hover.call(this, div, on_mouseout);
}
// ...
this.addEventListener('mouseout',on_mouseout,false);
}
function clear_hover(child, handler){
//remove the bubble div we made
child.parentNode.removeChild(child);
//remove the mouse out as we are now out
this.removeEventListener('mouseout',handler,false);
// ...
}
你就不能像这样调用clear\u hover(div)
?我可以。但我一直认为,查找孩子的父节点而不是仅仅传递这个,对浏览器来说会更费力。当然父节点一定会存在,毕竟我确实附加了一个div?@Dave这是第一次。但是,因为事件处理程序实际上没有被删除,所以它会一次又一次地尝试删除元素,以此类推。
function bubble_info(e){
var ...;
function on_mouseout() {
// pass a reference to the `function` itself
clear_hover.call(this, div, on_mouseout);
}
// ...
this.addEventListener('mouseout',on_mouseout,false);
}
function clear_hover(child, handler){
//remove the bubble div we made
child.parentNode.removeChild(child);
//remove the mouse out as we are now out
this.removeEventListener('mouseout',handler,false);
// ...
}