2012-02-07 4 views
137

私は分類foobarとDIV、およびunclassedであることDIV内のいくつかのdiv要素を持っていますが、私は彼らがfoobarクラスを継承しているとしますクリックイベントは子どもではなく、親DIVでのみ発生するのはどうですか?

$('.foobar').on('click', function() { /*...do stuff...*/ }); 

私はそれがどこかでクリックしたときにのみオフに解雇したいですDIVはその子のDIVではない。

答えて

315

e.targetthisと同じ要素の場合は、子孫をクリックしていません。

$('.foobar').on('click', function(e) { 
 
    if (e.target !== this) 
 
    return; 
 
    
 
    alert('clicked the foobar'); 
 
});
.foobar { 
 
    padding: 20px; background: yellow; 
 
} 
 
span { 
 
    background: blue; color: white; padding: 8px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class='foobar'> .foobar (alert) 
 
    <span>child (no alert)</span> 
 
</div>

+0

この回答は[this](http://stackoverflow.com/questions/9146163/jquery-closest-with-attribute-filter#comment11499568_9146163)のコメント – gdoron

+0

@gdoronについて説明しています。アダムはあまりにも親切です。 :) –

+0

あなたは私の[質問](http://stackoverflow.com/q/9193293/601179)... =) – gdoron

17
//bind `click` event handler to the `.foobar` element(s) to do work, 
//then find the children of all the `.foobar` element(s) 
//and bind a `click` event handler to them that stops the propagation of the event 
$('.foobar').on('click', function() { ... }).children().on('click', function (event) { 
    event.stopPropagation(); 
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler) 
}); 

これは.foobar要素(複数可)の子要素(複数可)のいずれかにclickイベントの伝播(バブリング)を停止しますので、イベントはしません.foobar要素に到達してイベントハンドラを起動します。ここで

はデモです:http://jsfiddle.net/bQQJP/

19

あなたはあなたの好意でバブリング使用することができます。

$('.foobar').on('click', function(e) { 
    // do your thing. 
}).on('click', 'div', function(e) { 
    // clicked on descendant div 
    e.stopPropagation(); 
}); 
+0

ではなくe.targetとthis.ref_nameを比較します。これは、私の特定のシナリオのための素晴らしいソリューションのようです子孫の ''要素にあります。ただ1つの問題があります:それらを真ん中でクリックすると、イベントが引き続き発生します(Google Chromeでテスト済み)。これを防止する変種はありますか? – cgogolin

2
$(".advanced ul li").live('click',function(e){ 
    if(e.target != this) return; 
    //code 
    // this code will execute only when you click to li and not to a child 
}) 
22

あなただけの新しいブラウザをターゲットに気にしない場合に動作し、別の方法があります。 CSSを追加するだけで、クリックをキャプチャしたいdivの子供にCSSを追加してください。

pointer-events: none; 

ここで私は同じ問題を抱えていたし、(他の回答に基づいて)このソリューション

$(".newsletter_background").click(function(e) { 
    if (e.target == this) { 
     $(".newsletter_background").hide(); 
    } 
}); 

基本的にはターゲットがdiv要素は、その後実行された場合言う思い付いた

http://caniuse.com/#feat=pointer-events

+2

これは最高のハックです、ありがとう – Rickie

+0

良い解決策、ありがとうございます。 – tulsluper

+1

私は「感謝」のコメントを書いてはならないことを知っているが、私はあなたのために足をキスすることができる:-) –

0

サポート表ですそれ以外の場合は何もしないでください(非表示にしないでください)

関連する問題