jQuery parent();函数 removeClass();不工作(错误)

jQuery parent(); function removeClass(); not working (bug)

我有一个投资组合,其中列出了投资组合项目。 我有 classes,所以当您单击该项目时,它会产生效果。 出于某种原因,当我单击减号按钮时,它不会删除 class 'on'.

这里是 jQuery:

  $('.portfolio-item').click(function() {
    $(this).addClass('on');
  });
  $('.minus').click(function() {
    $(this).closest('.portfolio-item').removeClass('on');
  });

这是设置的元素:

<div class="portfolio-item" style="margin-top: 5px; ">
   <div class="overlay">
      <h1>LOW POLY ISLANDS</h1>
      <h3>LOW POLY</h3>
   </div>
   <div class="about">
      <h1>LOW POLY ISLANDS</h1>
      <h3>LOW POLY</h3>

      <div class="descrip">
         This is a low poly island make in Blender and edited in Photoshop.
      </div>

      <div class="minus"></div>
      <div class="plus"></div>
    </div>
    <img src="https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/57909c29180525.55fc4b1875c26.png" width="100%" />
</div>

我该如何解决这个问题 - 我希望能够在单击 'minus' 时删除 class 'on'。

你需要使用e.stopPropagation()

$('.minus').click(function(e) {
      e.stopPropagation();
    $(this).closest('.portfolio-item').removeClass('on');
  });

DEMO

当您单击 minus 时,它会删除 class on。但是,与此同时,由于 minus 位于 portfolio-item 内,它会触发其 click 事件并将此 class 应用回去。

您可以使用 e.stopPropagation() 来禁用此行为。

根据文档,e.stopPropagation

prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

这是工作 JSFiddle demo。它看起来很糟糕,但展示了功能。