2014-09-12 59 views
-2

發生了什麼事:重視通過點擊按鈕點擊事件,身體沒有立即觸發它

  1. 用戶點擊按鈕
  2. 菜單打開(<li>的顯示器=塊)
  3. 關閉菜單功能連接到<body>
  4. 關閉菜單功能立即觸發並且菜單關閉

我附加了一個關閉菜單(隱藏li)到body(3)的功能,以便在菜單打開後,用戶可以通過單擊屏幕上的任何位置將其關閉。

問題是功能附加到body立即觸發按鈕點擊功能,所以菜單打開和關閉之前,用戶甚至看到它。

我使用jQuery 1.7的.on()函數來綁定事件。

有沒有人知道一個簡單的解決方案呢? 'bindAfterEvent'或者其他的東西。

代碼:

$(document).ready(function() { 
    $('#page-content div.center-block div:nth-child(1) ul li:nth-child(1)').on('click', openSubnav); 
}); 

openSubnav = function(e) { 
    // Shows all li tags and attaches close function to the body 
    e.preventDefault(); 
    $('#page-content div.center-block div:nth-child(1) ul li').show(); 
    $('body').on('click', closeSubnav); 
}; 

closeSubnav = function() { 
    // Hides all li tags except the first (used to open) 
    $('#page-content div.center-block div:nth-child(1) ul li').hide(); 
    $('#page-content div.center-block div:nth-child(1) ul li:nth-child(1)').show(); 
}; 
+3

代碼在哪裏? – melancia 2014-09-12 14:50:25

回答

1

像這樣的事情? (更新)

$('button').off('click').on('click', functione(e) { 
    // stop propagation to assure the body click won't be triggered 
    e.stopPropagation(); 
    $('div').show(); 
    $('body').off('click').on('click', function(e) { 
     // return false if the element clicked is the button that shows the menu 
     if($(e.target).is('button')) return false; 
     $('div').hide(); 
     $('body').off('click'); 
    }); 
});