jQuery .click () acara tidak berfungsi. Dari dua yang satu berfungsi, yang lainnya tidak [duplikat]

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>

Mengapa kode saya tidak berfungsi? Acara klik pertama berfungsi dengan baik tetapi yang kedua tidak berfungsi. Harap sarankan beberapa cara lain untuk melakukannya.

Jawaban

1 ZakariaAcharki Dec 19 2020 at 18:26

Anda dapat melampirkan acara ke kelas utamalike-unlike-btn dan menggunakan 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>