jQuery parent(); function removeClass(); not worki

2019-05-30 03:28发布

I have a portfolio where I list portfolio items. I have classes so when you click the item, it has an effect. For some reason, when I click the minus button, it doesn't remove the class 'on'.

Here is the jQuery:

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

and here is the element set up:

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

How do I fix this - I want to be able to remove the class 'on' when I click on 'minus'.

2条回答
劳资没心,怎么记你
2楼-- · 2019-05-30 04:18

you need to use e.stopPropagation()

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

DEMO

查看更多
成全新的幸福
3楼-- · 2019-05-30 04:28

When you click your minus it removes the class on. However, at the same time, as minus is located within portfolio-item, it triggers its click event and applies this class back.

You can use e.stopPropagation() to disable this behaviour.

According to documentation, e.stopPropagation

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

Here is the working JSFiddle demo. It looks awful, but demonstrates the functionality.

查看更多
登录 后发表回答