提问者:小点点

jquery如何在单击内容时从内容中删除类


我想在单击图标时从心形图标中删除类text-danger,但没有成功:

$(document).ready(function(){
  $('.blog-like-counter').on('click', function (e) {
    e.preventDefault();
    $(this).next('.heart-icon').removeClass('text-danger'); // remove red color heart icon  
  });
});

<div class="blog-like-counter">
    <p class="heart-icon text-danger">&#9829;</p>
</div>

https://jsfiddle.net/cp8ms2tu/1/


共2个答案

匿名用户

请使用find方法,因为next方法获取的是next元素而不是内部元素

      $('.blog-like-counter').on('click', function (e) {
        e.preventDefault();
        $(this).find('.heart-icon').removeClass('text-danger'); // remove red color heart icon
      });

匿名用户

使用children方法也可以解决这个问题,Next获取下一个元素,而不是下一个“child”元素。

    $(document).ready(function(){
  $('.blog-like-counter').on('click', function (e) {
    e.preventDefault();
    $(this).children('.heart-icon').removeClass('text-danger'); // remove red color heart icon  
  });
});