JQuery .click - 排除 div 内的特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10646047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery .click - exclude specific elements inside div
提问by supercoolville
I want .click to do nothing IF the user clicks <p>text</p>
inside the div, for everything else I want the div .click to work.
如果用户<p>text</p>
在 div 内单击,我希望 .click 不执行任何操作,对于其他所有我希望 div .click 工作的内容。
HTML:
HTML:
<div>
<span>yes</span>
<p>text</p>
</div>
Jquery:
查询:
<script>
$(document).ready(function() {
$("div").click(function() {
alert("woohoo!");
});
});
</script>
回答by mkoryak
$("div").click(function(e) {
if($(e.target).is('p')){
e.preventDefault();
return;
}
alert("woohoo!");
});
check the target of the click. this way you dont need to bind another event.
检查点击的目标。这样你就不需要绑定另一个事件。
回答by Fagner Brack
<script>
$( document ).ready(function() {
$( "div :not(p)" ).click(function( event ) {
alert( "woohoo!" );
});
});
</script>
This implies you don't care about text nodes as children of the <div>
container.
这意味着您不关心文本节点作为<div>
容器的子节点。
回答by xdazz
$("div > span").click(function() {
alert("woohoo!");
});
But you'd better provide ids for your html element.
但是您最好为您的 html 元素提供 id。