2017-08-18 4 views
1

jQueryのオーバーラップdivが文句を言わないのdivの隠されたのonclickを無効

jQuery('#warning').click(function() { 
 
    console.log('clicked at warning'); 
 
}); 
 

 
jQuery('#content').click(function() { 
 
    console.log('clicked at content'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="warning"> 
 
    <div id="content">This is the content</div> 
 
    dsfdfsdsfdsfdsfdsfdsfdsf 
 
</div>

フィドル:

https://jsfiddle.net/73jykhj0/は、残念ながら、あまりにもwarningでクリックトリガーcontentでクリックします。 warningでクリックを排除するにはどうすればよいですか?

+3

'するevent.stopPropagation()' – Satpal

+1

むしろ悪い習慣と考えられているイベントの伝播を停止 - あなたはバブルアップなどのイベントに依存しているページ上の他の機能を、持っているかもしれません。むしろ、イベントのターゲットがハンドラ関数内にあったものを確認し、それに基づいて何かを行うかどうかを判断する必要があります。 – CBroe

+1

コンテンツがクリックされた場合は機能を停止してください。このhttps://jsfiddle.net/73jykhj0/1/を参照してください。 –

答えて

7

防止イベントevent.stopPropagation()

jQuery('#warning').click(function() { 
 
    console.log('clicked at warning'); 
 
}); 
 

 
jQuery('#content').click(function(event) { 
 
    event.stopPropagation() 
 
    console.log('clicked at content'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="warning"> 
 
    <div id="content">This is the content</div> 
 
    dsfdfsdsfdsfdsfdsfdsfdsf 
 
</div>


それとも、あなたはニードフルを行い、その後event.targetを使用して、イベントのターゲットを確認することができますを使用してバブルアップから。

jQuery('#warning').click(function(event) { 
 
    if ($(event.target).is('#content')) { 
 
    return; 
 
    } 
 
    console.log('clicked at warning'); 
 
}); 
 

 
jQuery('#content').click(function() { 
 
    console.log('clicked at content'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="warning"> 
 
    <div id="content">This is the content</div> 
 
    dsfdfsdsfdsfdsfdsfdsfdsf 
 
</div>

2

下記を参照してください。コンテンツをクリックするとreturn falseが追加されます。

jQuery('#warning').click(function() { 
 
    alert('clicked at warning'); 
 
}); 
 

 
jQuery('#content').click(function() { 
 
    alert('clicked at content'); 
 
    return false; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="warning"> 
 
    <div id="content">This is the content</div> 
 
    dsfdfsdsfdsfdsfdsfdsfdsf 
 
</div>

関連する問題