jQuery .click () 이벤트가 작동하지 않습니다. 둘 중 하나가 작동하고 다른 하나가 작동하지 않음 [중복]

Dec 19 2020

$('.like-btn').click((e) => { e.target.classList = 'like-unlike-btn unlike-btn far fa-heart'; }); $('.unlike-btn').click((e) => {
  e.target.classList = 'like-unlike-btn like-btn far fa-heart';
});
.like-unlike-btn {
  color: #fb3958;
  font-size: 2rem;
  position: absolute;
  top: 0;
  left: 10px;
  cursor: pointer;
}

.like-unlike-btn:hover {
  color: rgb(252, 11, 11);
}

.unlike-btn {
  font-weight: bold;
}

.like-btn {
  font-weight: normal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"
    integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

<i class="like-unlike-btn like-btn far fa-heart"></i>

내 코드가 작동하지 않는 이유는 무엇입니까? 첫 번째 클릭 이벤트는 제대로 작동하지만 두 번째는 작동하지 않습니다. 다른 방법을 제안하십시오.

답변

1 ZakariaAcharki Dec 19 2020 at 18:26

이벤트를 기본 클래스에 연결 like-unlike-btn하고 toggleClass대신 사용할 수 있습니다 .

$('.like-unlike-btn').on('click', function(e) { $(this).toggleClass('unlike-btn like-btn');
});
.like-unlike-btn {
  color: gray;
  font-size: 2rem;
  position: absolute;
  top: 0;
  left: 10px;
  cursor: pointer;
}

.like-unlike-btn:hover {
  color: red !important;
}

.like-btn {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

<i class="like-unlike-btn like-btn far fa-heart"></i>