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

可紊 提交于 2019-12-08 04:20:09

问题


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


回答1:


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.




回答2:


you need to use e.stopPropagation()

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

DEMO



来源:https://stackoverflow.com/questions/33749372/jquery-parent-function-removeclass-not-working-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!