2017-03-01 12 views
-1

私はメニューを隠して表示するための簡単なjQueryを持っています。メニューの外側をクリックすると、それを隠すことになっています。しかし、メニューのトリガーターゲット(リンクなど)をクリックすると、隠すだけでなく、メニューが非表示になります。jQueryがトリガーを2回発しているのはなぜですか?

var notifyMenu = $(".notifyMenu .menu"); 

if (!notifyMenu.is(e.target) // if the target of the click isn't the container... 
&& notifyMenu.has(e.target).length === 0) // ... nor a descendant of the container 
{ 
    notifyMenu.hide(); 
    screenOverlay.hide(); 

} 


$('.notifyMenu > a').click(function(event) { 
    var menuID = $(this).parent().prop("id"); 
    var notifyMenu = $('#' + menuID + ' .menu'); 

    if (notifyMenu.is(':visible')) { 
     screenOverlay.fadeOut(); 
     notifyMenu.fadeOut('fast'); 
    } else { 
     // Show screenoverlay if on mobile 
     if (ftrNav.is(':visible')) { 
      screenOverlay.fadeIn('fast'); 
     } 
     notifyMenu.fadeIn('fast'); 
    } 

    event.preventDefault(); 

}); 

HTMLは次のようになります。

<li id="userLI" class="notifyMenu"> 
      <a href="/player/profile"> 
       &nbsp; 
       <div class="profilePhoto">JM</div> 
       <span class="fa fa-angle-down"></span> <div class="numVal"></div> 
      </a> 

      <div class="menu playerMenu" style="display: block;"> 
       <div class="upArrow"></div> 
       <ul> 
        <li class="playerDetails"> 
         <div class="name">Jon Marus</div> 
         <div class="access"> 
          MANAGER (Spare)      </div> 
        </li> 
        <li><a href="/player/profile/"><div class="icon fa fa-user-circle-o" title="Player Profile"></div> Profile</a></li> 
        <li><a href="/player/notifications"><div class="icon fa fa-bell"></div> Notifications</a></li> 
        <li><a href="/player/password"><div class="icon fa fa-lock"></div> Change Password</a></li> 
        <li><a href="/logout"><div class="icon fa fa-sign-out" title="Logout"></div> Logout</a></li> 
       </ul> 
      </div> 
     </li> 

任意のアイデア?

答えて

1

DOMイベントの仕組みです。それぞれのイベントはすべてドキュメントオブジェクトに伝播します。

したがって、onclickメニューにevent.stopPropagation()を追加する必要があります。メニューがクリックされると、ドキュメントのonclickイベントハンドラは呼び出されません。

例:

$(document).on('click', function() { 
    //Hide the menu etc... 
    $('.notifyMenu .menu').hide(); 
} 

$('.notifyMenu .menu').on('click', function(e) { 
    //Show or toggle code goes here 
    $('.notifyMenu .menu').show(); 
    e.stopPropagation(); 
}); 
+0

私はそれを試していたことを言及している必要があります。 onclickを次のように変更しました: 'code' if(!notifyMenu.is(e.target)//クリックのターゲットがコンテナでない場合... && notifyMenu.has(e.target).length == = 0)// ...コンテナの子孫でもない { notifyMenu.hide(); screenOverlay.hide(); } 'code' – Jon

+0

私はコメントにひどいです。 – Jon

+1

私は例を追加しました。これは古典的な汎用ドロップダウン手法です –

関連する問題