2016-05-30 7 views
0

私は、ボタンをクリックして開いているメニューを持っています。開いているメニューの外をクリックするたびに、私はそれを閉じるように頼まれました。jquery閉じるメニュー(またはモーダル)のための.not()は機能しません。

これは、「それを閉じるために、モーダルの外側をクリックし、」行動に実質的に同一であるが、固定されたメニューヘッダに適用されます。

私はこのような何かを考えた:私が得る、クリックごと)にconsole.log火災 2、

1)私はをクリックしどこ:

$('*').not('.header').on('click', function(){ 
     //close menu function 
    console.log("close the menu") 
}); 

が、それは多くの方法で働いていません3 console.logが起動しました。ここで

はフィドルです:https://jsfiddle.net/Ln1wabqq/1/

私は

  • $('*:not(".header")')
  • $('*').not('.header, .header *')
  • $('').not('.header')

が、私はまったく同じ出力を得るに$('*')を変更しようとしました。私はここで完全に間違った道を歩いていますか?

$(document).click(function(event) { 
    if(!$(event.target).closest('.header').length){ 
     // click outside .header 
    } 
}); 

答えて

3

ため

どうもありがとうそれを要素とその子孫/祖先にフックします。クリック気泡として、ハンドラは各レベルで起動されます。

あなたはすべての要素にフックして、それを処理したい場合は、.headerの子孫である要素のクリックを無視するハンドラを使用することができます。

$("*").on("click.closemenu", function() { 
    if ($(this).closest(".header").length) { 
     // This is .header or a descendant, ignore 
    } else { 
     // Close menu 

     // Remove this handler (if desired) 
     $("*").off("click.closemenu"); 
    } 
    return false; // Either way, prevent further bubbling and any default action 
}); 
1

クリックバブル、文書内のすべての要素にclickをフックして、あなたがしている:あなたはこのように要素の外側をクリックを検出することができ、あなたの助け

0

あなたがこの試すことができます:

 $("body :not(".header")").clicked(your function) 
0
を .header 直接の子であると仮定すると

、使用してみてください:

$('body>*').not('.header').on('click', function(){ 
    //close menu function 
    console.log("close the menu") 
}); 
はここFiddle

0

あなたがfiltreだけの要素がウィッヒ親クラスとして「ヘッダ」を持って、必要なものを実行する方法を参照してください。

$(document).on('click', 'div', function(e){ 
    if ($(this).parent('.header').length > 0) { 
     //close menu function 
     console.log("close the menu"); 
    } 
}); 
関連する問題