更改 class 名称和更改事件响应

Changing class name and changing event response

我有一个带有 class add-to-favorite 的按钮,单击后 class 更改为 remove-from-favorite 并且文件被添加到收藏夹。当用户再次点击该按钮时,它已经将 remove-from-favorite 和 class 更改为 add-to-favorite 并且该文件必须从收藏夹中删除,但事实并非如此。即使 class 是 add-to-favorite;,该按钮的作用也与 remove-from-favorite 相同。有什么想法吗?

代码如下:

<button type="button" class="add-to-favorite" name="button"><i class="material-icons">favorite_border</i></button>

这是 add-to-favorite

的 Javascript 代码
$(".add-to-favorite").on("click", function(event) {
var clicked_button = $(this); 
    clicked_button.html("<i class='material-icons'>close</i>");
    clicked_button.removeClass('add-to-favorite');
    clicked_button.addClass('remove-from-favorite');
 })

这里是 javascript remove-from-favorite

$(".remove-from-favorite").on("click", function(event) {
var clicked_button = $(this);
    clicked_button.html("<i class='material-icons'>favorite_border</i>");
    clicked_button.removeClass('remove-from-favorite');
    clicked_button.addClass('add-to-favorite');
 })

点击事件只需使用$(document).on():

$(document).on("click",".add-to-favorite", function(event) {
    var clicked_button = $(this); 
        clicked_button.html("<i class='material-icons'>close</i>");
        clicked_button.removeClass('add-to-favorite');
        clicked_button.addClass('remove-from-favorite');
 });

 $(document).on("click",".remove-from-favorite", function(event) {
    var clicked_button = $(this);
        clicked_button.html("<i class='material-icons'>favorite_border</i>");
        clicked_button.removeClass('remove-from-favorite');
        clicked_button.addClass('add-to-favorite');
 });