我想点击一个孩子,但是如果我点击他的父母,则不会触发点击。这是我尝试过的。
$("#parent").css("pointer-events","none");
$("#parent").click(function(e) {
e.stopPropagation();
console.log('Clicked parent')
});
$("#child").click(function(e) {
console.log('Clicked child');
});
#parent{
width: auto;
height: 20px;
background-color:red;
}
#child{
width:20px;
height:20px;
background-color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div id="child"></div>
</div>
我想删除父级而不是子级的onclick处理程序。
答案 0 :(得分:1)
$("#parent *:not(#child)")
可以做到
$(document).ready(function(){
$("#parent *:not(#child)").css("pointer-events","none");
$("#parent *:not(#child)").on('click',function(e) {
e.stopPropagation();
console.log('Clicked parent')
});
$("#child").on('click',function(e) {
console.log('Clicked child');
});
});
#parent{
width: auto;
height: 20px;
background-color:red;
}
#child{
width:20px;
height:20px;
background-color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent" style="">
<div id="child"></div>
</div>
答案 1 :(得分:0)
将e.stopPropagation();
添加到子click
处理程序
$("#parent").click(function(e) {
console.log('Clicked parent');
});
$("#child").click(function(e) {
console.log('Clicked child');
e.stopPropagation();
});
#parent {
width: auto;
height: 20px;
background-color: red;
}
#child {
width: 20px;
height: 20px;
background-color: green;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div id="child"></div>
</div>