2014-02-24 54 views
0

我想通過點擊打開一些菜單時,將點擊功能綁定到文檔。 問題是,當觸發第一個事件'點擊菜單'時,附加到文檔的功能已被相同的事件觸發並關閉菜單。如何解決這個問題。我的代碼是這樣的:爲什麼文檔立即點擊偵聽器觸發器?

$('#openMenu').bind('click touchend', function(e){ 
    e.preventDefault(); 
    $('.openMobMenu').removeClass('openMobMenu');//Close All elements 
    var _this=$('#headMenu') 
    _this.addClass('openMobMenu'); 

    $(document).bind('click touchend',{elem:_this},hideElementMob); 
}); 

// bind click event listner to the document 
function hideElementMob(e){ 

    var th=e.data.elem;//Get the open element 
    var target=$(e.target);//Get the clicked target 

     //Check the target and close the element if need 
    if(target.parents('.openMobMenu').length==0) { 
     th.removeClass('openMobMenu');//close the element if need 
     //Unbind listner after closing the element 
     $(document).unbind('click touchend'); 
    } 
} 

謝謝你提前!

+0

'bind'被取代。使用'on'。 –

+1

每次單擊以打開菜單時,都會將單擊事件綁定到文檔。檢查一下你是否點擊了隱藏元素函數中的#openMenu會更好。 – putvande

回答

2

嘗試添加密切處理器有一點延遲:

setTimeout(function(){ 
    $(document).bind('click touchend',{elem:_this},hideElementMob); 
}, 10); 


隨着揚德沃夏克建議,你應該使用。對()附加事件。

UPDATE
我意識到我沒有回答全部問題,所以這裏是一些改進的「它爲什麼這樣的表現」部分:

當點擊事件上#openMenu發生,相關的處理程序首先執行。這將點擊事件綁定到文檔主體本身。
之後,事件冒泡,因此#openMenu的父母也會收到點擊事件,並且由於document.body#openMenu的父親,因此它還會收到點擊事件並關閉彈出式窗口。

要取消事件冒泡,您還可以在事件處理程序中的任意位置調用e.stopPropagation();。 (也許它是一個比setTimeout更清潔的解決方案)

+0

謝謝,超時工作! –

相關問題