我想通過點擊打開一些菜單時,將點擊功能綁定到文檔。 問題是,當觸發第一個事件'點擊菜單'時,附加到文檔的功能已被相同的事件觸發並關閉菜單。如何解決這個問題。我的代碼是這樣的:爲什麼文檔立即點擊偵聽器觸發器?
$('#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');
}
}
謝謝你提前!
'bind'被取代。使用'on'。 –
每次單擊以打開菜單時,都會將單擊事件綁定到文檔。檢查一下你是否點擊了隱藏元素函數中的#openMenu會更好。 – putvande