私は分類foobar
とDIV、およびunclassedであることDIV内のいくつかのdiv要素を持っていますが、私は彼らがfoobar
クラスを継承しているとしますクリックイベントは子どもではなく、親DIVでのみ発生するのはどうですか?
$('.foobar').on('click', function() { /*...do stuff...*/ });
私はそれがどこかでクリックしたときにのみオフに解雇したいですDIVはその子のDIVではない。
私は分類foobar
とDIV、およびunclassedであることDIV内のいくつかのdiv要素を持っていますが、私は彼らがfoobar
クラスを継承しているとしますクリックイベントは子どもではなく、親DIVでのみ発生するのはどうですか?
$('.foobar').on('click', function() { /*...do stuff...*/ });
私はそれがどこかでクリックしたときにのみオフに解雇したいですDIVはその子のDIVではない。
e.target
がthis
と同じ要素の場合は、子孫をクリックしていません。
$('.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>
//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
要素に到達してイベントハンドラを起動します。ここで
あなたはあなたの好意でバブリング使用することができます。
$('.foobar').on('click', function(e) {
// do your thing.
}).on('click', 'div', function(e) {
// clicked on descendant div
e.stopPropagation();
});
ではなくe.targetとthis.ref_nameを比較します。これは、私の特定のシナリオのための素晴らしいソリューションのようです子孫の ''要素にあります。ただ1つの問題があります:それらを真ん中でクリックすると、イベントが引き続き発生します(Google Chromeでテスト済み)。これを防止する変種はありますか? – cgogolin
$(".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
})
あなただけの新しいブラウザをターゲットに気にしない場合に動作し、別の方法があります。 CSSを追加するだけで、クリックをキャプチャしたいdivの子供にCSSを追加してください。
pointer-events: none;
ここで私は同じ問題を抱えていたし、(他の回答に基づいて)このソリューション
$(".newsletter_background").click(function(e) {
if (e.target == this) {
$(".newsletter_background").hide();
}
});
基本的にはターゲットがdiv要素は、その後実行された場合言う思い付いた
サポート表ですそれ以外の場合は何もしないでください(非表示にしないでください)
この回答は[this](http://stackoverflow.com/questions/9146163/jquery-closest-with-attribute-filter#comment11499568_9146163)のコメント – gdoron
@gdoronについて説明しています。アダムはあまりにも親切です。 :) –
あなたは私の[質問](http://stackoverflow.com/q/9193293/601179)... =) – gdoron