删除父级上的单击事件,但子级可单击

时间:2018-12-26 15:30:23

标签: javascript jquery html

我想点击一个孩子,但是如果我点击他的父母,则不会触发点击。这是我尝试过的。

$("#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处理程序。

2 个答案:

答案 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>