2013-07-31 52 views
0

我有一個正在等待事件轉移的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 = 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); 
} 

任何一個能看到的錯誤我在寫這裏,只是不能工作了,爲什麼這一切都錯了鼠標了。

開發工具顯示Cannot call method 'removeChild' of null

+0

你就不能調用clear_hover這樣'clear_hover(DIV) '? – fmodos

+0

嗯,我可以。但我總是認爲查找孩子的父節點而不是僅僅傳遞'this'會對瀏覽器造成更多的負擔。 – Sir

回答

1

該錯誤提示child.parentNode == null。因此,該元素沒有要從中刪除的parentNode

if (child.parentNode) 
    child.parentNode.removeChild(child); 

但是,那隻能修復症狀。實際的問題是事件處理程序沒有被刪除,因此它會繼續運行,並隨後發生mouseout事件。

儘管以下功能類似,但它們需要保持一致才能成功刪除。

this.addEventListener('mouseout',function(){clear_hover.call(this,div);},false); 
this.removeEventListener('mouseout',function(){clear_hover.call(this,div);},false); 

所以,你需要保存到function的引用將其刪除:

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); 

    // ... 
} 
+0

當然一個parentNode必然存在我畢竟追加到一個div? – Sir

+0

@Dave這是第一次。但是,由於事件處理程序並未被實際刪除,因此它會嘗試再次刪除該元素,等等。 –

+0

現在就開始工作吧!謝謝@Jon! – Sir