jquery - 单击父进行操作,但对于子进程没有

时间:2016-11-09 09:51:44

标签: jquery html css

我在html中有这个元素

<div class="item">
  <div class="showed">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe magnam, ea est quo voluptate a necessitatibus facere explicabo. Doloribus odio, atque voluptatibus. Libero est, eius totam incidunt eaque debitis reprehenderit.</p>
    <a href="#" class="nope">AA</a>
  </div>
  <div class="hided">Im hided</div>
</div>

我隐藏div与隐藏css的班级

.item {
  border:  2px solid black;
  margin: 20px;
  cursor: pointer;
}

.hided {
  display: none;
}

使用jQuery,我允许切换显示.hidded div。

$(".item").on("click", function(){
  $(this).find(".hided").toggle();
});

我不知道如果用户点击链接元素(使用.nope类),如何避免切换。

2 个答案:

答案 0 :(得分:0)

检查event.target不是.nope元素。

&#13;
&#13;
$(".item").on("click", function(e) {
  if ($(e.target).is(':not(.nope)'))
  // or if (!$(e.target).hasClass('nope'))
    $(this).find(".hided").toggle();
});
&#13;
.item {
  border: 2px solid black;
  margin: 20px;
  cursor: pointer;
}
.hided {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
  <div class="showed">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe magnam, ea est quo voluptate a necessitatibus facere explicabo. Doloribus odio, atque voluptatibus. Libero est, eius totam incidunt eaque debitis reprehenderit.</p>
    <a href="#" class="nope">AA</a>
  </div>
  <div class="hided">Im hided</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以尝试这样做,e.target您当前点击的元素hasClass会更改该元素上存在的nope类。

$(".item").on("click", function(e){
  if(!$(e.target).hasClass('nope'))
  {
    $(this).find(".hided").toggle();
  }
});
.item {
  border:  2px solid black;
  margin: 20px;
  cursor: pointer;
}

.hided {
  display: none;
}
<div class="item">
  <div class="showed">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe magnam, ea est quo voluptate a necessitatibus facere explicabo. Doloribus odio, atque voluptatibus. Libero est, eius totam incidunt eaque debitis reprehenderit.</p>
    <a href="#" class="nope">AA</a>
  </div>
  <div class="hided">Im hided</div>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>