0

move over イベントを待っている 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 = 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

4

1 に答える 1

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

    // ...
}
于 2013-07-31T05:32:21.740 に答える